1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

string.Compareの挙動がおかしい [C#]

Last updated at Posted at 2019-06-09

#"1-1"と"101"、"111"の比較結果が変

ファイル名のソート順がなんか変だなと思って原因を調べてみたらどうもstring.Compareがおかしいっぽい。

"-" < "0" < "1" なので、"1-1" < "101" < "111"になるはずだけど、"101" < "1-1" < "111"になってしまう。謎。

追記: string.Compare はカルチャ依存の比較を行い、ハイフンを無視した文字列で比較を行っている模様。string.CompareOrdinal を使えば良いらしい。

###テストコード

using System;

class StringCompare
{
    static void Main()
    {
        Console.WriteLine("string.Compare(\"-\",\"0\") = {0}", string.Compare("-","0"));
        Console.WriteLine("string.Compare(\"-\",\"1\") = {0}", string.Compare("-","1"));
        Console.WriteLine("string.Compare(\"0-\",\"00\") = {0}", string.Compare("0-","00"));
        Console.WriteLine("string.Compare(\"0-\",\"01\") = {0}", string.Compare("0-","01"));
        Console.WriteLine("string.Compare(\"1-\",\"10\") = {0}", string.Compare("1-","10"));
        Console.WriteLine("string.Compare(\"1-\",\"11\") = {0}", string.Compare("1-","11"));
        Console.WriteLine("string.Compare(\"0-0\",\"000\") = {0}", string.Compare("0-0","000"));
        Console.WriteLine("string.Compare(\"0-0\",\"010\") = {0}", string.Compare("0-0","010"));
        Console.WriteLine("string.Compare(\"1-0\",\"100\") = {0}", string.Compare("1-0","100"));
        Console.WriteLine("string.Compare(\"1-0\",\"110\") = {0}", string.Compare("1-0","110"));
        Console.WriteLine("string.Compare(\"1-1\",\"101\") = {0}", string.Compare("1-1","101")); // これのみ 1 他 -1
        Console.WriteLine("string.Compare(\"1-1\",\"111\") = {0}", string.Compare("1-1","111"));
    }
}

###実行結果

string.Compare("-","0") = -1
string.Compare("-","1") = -1
string.Compare("0-","00") = -1
string.Compare("0-","01") = -1
string.Compare("1-","10") = -1
string.Compare("1-","11") = -1
string.Compare("0-0","000") = -1
string.Compare("0-0","010") = -1
string.Compare("1-0","100") = -1
string.Compare("1-0","110") = -1
string.Compare("1-1","101") = 1
string.Compare("1-1","111") = -1
1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?