LoginSignup
20
20

More than 5 years have passed since last update.

C# の IndexOf における長音符と「ゝ」について

Last updated at Posted at 2014-09-18

ここで問題です

以下のコードを実行すると何が表示されるでしょうか?

static void Main(string[] args)
{
    string s1 = "あゝ人生に涙あり";
    string s2 = "あー夏休み";
    Console.WriteLine(s1.IndexOf("ゝ"));
    Console.WriteLine(s1.IndexOf("ー"));
    Console.WriteLine(s1.IndexOf("ー"));
    Console.WriteLine(s2.IndexOf("ゝ"));
    Console.WriteLine(s2.IndexOf("ー"));
    Console.WriteLine(s2.IndexOf("ー"));
}

正解はこちら

long1.png

( ゚д゚)

どういうことなの

原因は IndexOf のデフォルトが CurrentCulture だから
これだと 厳密さを要求しない比較 になる
同様のケースでは こんな事案
しかしまさかこんなものまで……

どうすればいいの

以下のように比較方法を Ordinal (=単純なバイト比較)にしてやればいい

static void Main(string[] args)
{
    string s1 = "あゝ人生に涙あり";
    string s2 = "あー夏休み";
    Console.WriteLine(s1.IndexOf("ゝ", StringComparison.Ordinal));
    Console.WriteLine(s1.IndexOf("ー", StringComparison.Ordinal));
    Console.WriteLine(s1.IndexOf("ー", StringComparison.Ordinal));
    Console.WriteLine(s2.IndexOf("ゝ", StringComparison.Ordinal));
    Console.WriteLine(s2.IndexOf("ー", StringComparison.Ordinal));
    Console.WriteLine(s2.IndexOf("ー", StringComparison.Ordinal));
}

この実行結果がこちら
もう Ordinal がデフォルトでいいんじゃないかな……?

long2.png

結論

StringComparison ちゃんと指定しましょうね

(追記)ブルータスお前もか

他にも長音符とみなされるものがありそうな雰囲気だったので調べてみました

static void Main(string[] args)
{
    string s1 = "あー夏休み";
    Console.WriteLine("ゝ:" + s1.IndexOf("ゝ"));
    Console.WriteLine("ー:" + s1.IndexOf("ー"));
    Console.WriteLine("ー :" + s1.IndexOf("ー"));
    Console.WriteLine("~:" + s1.IndexOf("~"));
    Console.WriteLine("~ :" + s1.IndexOf("~"));
    Console.WriteLine("々:" + s1.IndexOf("々"));
    Console.WriteLine("ゞ:" + s1.IndexOf("ゞ"));
    Console.WriteLine("ヽ:" + s1.IndexOf("ヽ"));
    Console.WriteLine("ヾ:" + s1.IndexOf("ヾ"));
    Console.WriteLine("- :" + s1.IndexOf("-"));
    Console.WriteLine("-:" + s1.IndexOf("-"));
    Console.WriteLine("―:" + s1.IndexOf("―"));
    Console.WriteLine("‐:" + s1.IndexOf("‐"));
    Console.WriteLine("= :" + s1.IndexOf("="));
    Console.WriteLine("=:" + s1.IndexOf("="));
    Console.WriteLine("_:" + s1.IndexOf("_"));
    Console.WriteLine("_ :" + s1.IndexOf("_"));
}

この結果がこちら

long3.png

( ゚д゚)

( ゚д゚ )

どうやら が長音符とみなされるようです
探せばもっとあるかも……

20
20
4

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
20
20