LoginSignup
3
3

More than 5 years have passed since last update.

std.string

Posted at

D言語のstringモジュールについて公式サイトをみてあんましっくりこなかった部分を逐一まとめます.

文字列検索

import std.stdio, std.string;

void main()
{
    string c = "abcdefghijklabcdefghijkl";
    //indexOf : 最初の出現位置を返す
    assert(c.indexOf("cd") == 2);
    assert(c.indexOf("Cd") == -1);
    //n文字以降の文字列を探索
    assert(c.indexOf("abc",5) == 12);
    //大文字小文字を区別するときはCaseSensitiveを使います
    assert(c.indexOf("Cd",CaseSensitive.yes) == -1);
    assert(c.indexOf("Cd",CaseSensitive.no) == 2);

    //lastIndexOf : 最後の出現位置を返す
    assert(c.lastIndexOf("cd") == 14);

    //"edc"のうちどれかがあった最初位置を返す
    assert(c.indexOfAny("edc") == 2);
    assert(c.indexOfAny("edc",10) == 14);
    //"edc"のうち一番最後にあった文字の位置を返すassert(c.lastIndexOfAny("edc") == 16); 

    //探している文字列以降の文字列を返す
    //algorithm.searchingが必要
    import std.algorithm.searching;
    assert(c.find("def") == "defghijklabcdefghijkl");

    //見つかったらtrueを返す
    assert(c.canFind("def") == true);


    //文字カウント
    //'a', 'b'または'c'がある数を数える
    assert(c.countchars("abc") == 6);
    //"abc"がある数を数える
    assert(c.count("abc") == 2);

}

文字の書き換え

import std.stdio, std.string;
import std.array : appender;

//ネットで拾った
//同じ文字列を削除する
// Must keep the original order of the items.
// Slow implementation that shows the semantics.
T[] noDupes(T)(in T[] s) {
      import std.algorithm: canFind;
      T[] result;
      foreach (T c; s)
          if (!result.canFind(c))
              result ~= c;
      return result;
}

void main()
{
    string c = "abcdefghijklabcdefghijkl";

    //'a','d'または'c'を削除
    assert(c.removechars("adc") == "befghijklbefghijkl");


    //文字列の入れ替え
    string buf;
    auto transTable1 = makeTransTable("eo5", "57q");
    buf = translate("hello world", transTable1);
    assert(buf == "h5ll7 w7rld");

    buf = translate("hello world", transTable1, "low");
    assert(buf == "h5 rd");

    assert("AAAA".noDupes == "A");
    assert("AAAA".squeeze == "A");
    assert("ABAC".noDupes == "ABC");
    assert("ABAC".squeeze == "ABAC");

   //他モジュールが必要な処理
   import std.algorithm.searchiing;
   //文字を区切る
   auto a = "Carl Sagan Memorial     Station";
   auto r = findSplit(a, "Velikovsky");
   assert(r[0] == a);
   assert(r[1].empty);
   assert(r[2].empty);
   r = findSplit(a, " ");
   assert(r[0] == "Carl");
   assert(r[1] == " ");
   assert(r[2] == "Sagan Memorial Station");
   auto r1 = findSplitBefore(a, "Sagan");
   assert(r1[0] == "Carl ", r1[0]);
   assert(r1[1] == "Sagan Memorial Station");
   auto r2 = findSplitAfter(a, "Sagan");
   assert(r2[0] == "Carl Sagan");
   assert(r2[1] == " Memorial Station");
}

参考:
noDupesのフォーラム

他の機能

英語の公式サイトがリニューアルしたみたいでわかりやすくなっています. こちらを参考にすると良いでしょう

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3