我需要一种方法来检查两个字符串,以查看它们中是否有相同的单词但位置不同。我只需要单词中没有单词的数量,而不是实际单词。例如:字符串1为“这是乱序测试”,字符串2为“这是乱序测试”将返回1,因为一个单词乱序。
我从以下代码开始:
public int OutOfOrder(string string1, string string2)
{
var search1 = string1.Split(' ');
var search2 = string2.Split(' ');
var OutOfOrder = 0;
for (int i = 0; i < search1.Count() - 1; i++)
{
if (search2.Contains(search1[i]))
{
for (int j=0; j < search2.Count()-1; j++)
{
if(search1[i] == search2[j] && i == j)
{
continue;
}
else if (search1[i] == search2[j] && i != j)
{
OutOfOrder++;
break;
}
}
}
}
return OutOfOrder;
}
但是,遇到第一个后,一切都乱了,返回的数字不正确。
做到了
public static int OutOfOrder(string a, string b){
//not out of order issuex`
if (a.Length != b.Length) return -1;
foreach(string str in a.Split(' ')){
//not out of order issue
if (!b.Contains(str)) return -1;
}
//if out of order issue...
int count=0;
string[] awords = a.Split(' ');
string[] bwords = b.Split(' ');
for(int i=0; i<bwords.Length; i++){
if (!awords[i].Equals(bwords[i])) count++;
}
return (int)Math.Ceiling(0.0f + count/2);
//if one is out of order, then it's expected it renders another out of order too.
//so we need to divide it by 2 to get the one disturbing.
//and ceiling is used to help for odd number of words
}
现在测试
public static void Main(string[] args)
{
string a = "This solves the problem";
string b = "This solves problem the";
Console.WriteLine(OutOfOrder(a, b));
}
输出1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句