如何将数字字符串整理为数字?

Joa*_*nge 11 .net c# string comparison

如果你有像这样的字符串:

"file_0"
"file_1"
"file_2"
"file_3"
"file_4"
"file_5"
"file_6"
"file_11"
Run Code Online (Sandbox Code Playgroud)

如何对它们进行排序,使"file_11"不会出现在"file_1"之后,而是出现在"file_6"之后,因为11> 6.

我是否必须解析字符串并将其转换为数字?

Win7中的Windows资源管理器按我想要的方式对文件进行排序.

Mar*_*ell 12

我是否必须解析字符串并将其转换为数字?

基本上,是的; 但LINQ可能有所帮助:

var sorted = arr.OrderBy(s => int.Parse(s.Substring(5)));
foreach (string s in sorted) {
    Console.WriteLine(s);
}
Run Code Online (Sandbox Code Playgroud)


Guf*_*ffa 10

要处理任何类型格式的混合字符串和数字的排序,您可以使用这样的类将字符串拆分为字符串和数字组件并进行比较:

public class StringNum : IComparable<StringNum> {

   private List<string> _strings;
   private List<int> _numbers;

   public StringNum(string value) {
      _strings = new List<string>();
      _numbers = new List<int>();
      int pos = 0;
      bool number = false;
      while (pos < value.Length) {
         int len = 0;
         while (pos + len < value.Length && Char.IsDigit(value[pos+len]) == number) {
            len++;
         }
         if (number) {
            _numbers.Add(int.Parse(value.Substring(pos, len)));
         } else {
            _strings.Add(value.Substring(pos, len));
         }
         pos += len;
         number = !number;
      }
   }

   public int CompareTo(StringNum other) {
      int index = 0;
      while (index < _strings.Count && index < other._strings.Count) {
         int result = _strings[index].CompareTo(other._strings[index]);
         if (result != 0) return result;
         if (index < _numbers.Count && index < other._numbers.Count) {
            result = _numbers[index].CompareTo(other._numbers[index]);
            if (result != 0) return result;
         } else {
            return index == _numbers.Count && index == other._numbers.Count ? 0 : index == _numbers.Count ? -1 : 1;
         }
         index++;
      }
      return index == _strings.Count && index == other._strings.Count ? 0 : index == _strings.Count ? -1 : 1;
   }

}
Run Code Online (Sandbox Code Playgroud)

例:

List<string> items = new List<string> {
  "item_66b",
  "999",
  "item_5",
  "14",
  "file_14",
  "26",
  "file_2",
  "item_66a",
  "9",
  "file_10",
  "item_1",
  "file_1"
};

items.Sort((a,b)=>new StringNum(a).CompareTo(new StringNum(b)));

foreach (string s in items) Console.WriteLine(s);
Run Code Online (Sandbox Code Playgroud)

输出:

9
14
26
999
file_1
file_2
file_10
file_14
item_1
item_5
item_66a
item_66b
Run Code Online (Sandbox Code Playgroud)


Joe*_*oey 9

您可以导入StrCmpLogicalW函数并使用它来对字符串进行排序.这与Explorer本身用于文件名的功能完全相同.

但是,如果您不想要P/Invoke或在其他系统上保持兼容,则无法帮助您.


You*_*sef 6

以下基于Joey建议的代码适用于我(扩展方法为string []):

public static void SortLogical(this string[] files)
{
    Array.Sort<string>(files, new Comparison<string>(StrCmpLogicalW));
}

[DllImport("shlwapi.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
private static extern int StrCmpLogicalW(String x, String y);
Run Code Online (Sandbox Code Playgroud)