【发布时间】:2021-06-04 05:12:38
【问题描述】:
我正在测试以自定义字母顺序对数组进行排序的代码,但由于某种原因,每次我运行程序时,ordem 都不会排序
主代码
using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
string[] myArray = {"bbjcsnmh" , "kkr"};
Array.Sort(myArray, MySorter.CompareStrings);
foreach(string s in myArray)
{
Console.WriteLine(s);
}
}
}
自定义排序器
using System;
using System.Collections;
class MySorter
{
public static int CompareStrings(string a, string b)
{
var newAlphabetOrder = "kbwrqdnfxjmlvhtcgzps";
if(newAlphabetOrder.IndexOf((string) a) < newAlphabetOrder.IndexOf((string) b))
return -1;
return newAlphabetOrder.IndexOf((string) a) >
newAlphabetOrder.IndexOf((string) b) ? 1 : 0;
}
}
【问题讨论】:
-
您需要搜索每个字符的索引的字母表,而不是整个输入字符串
-
所以我需要将我的字母转换成一个字符数组?
-
没有。输出您从
IndexOf获得的实际索引:您会看到您总是得到“-1”。所以你需要一一查找每个输入字符串中每个字符的索引并进行比较。 -
实际上你可以先检查字符是否相等,然后再进行查找。
-
谢谢,我已经看到我的错误了,现在它可以正常工作了