在C#中,如何比较两个字符串中的字符。
例如,假设我有这两个字符串
“ bc3231dsc”和“ bc3462dsc”
如何以编程方式找出字符串
都以“ bc3”开头并以“ dsc”结尾?
因此,给定的将是两个变量:
var1 = "bc3231dsc";
var2 = "bc3462dsc";
比较从var1到var2的每个字符后,我希望输出为:
leftMatch = "bc3";
center1 = "231";
center2 = "462";
rightMatch = "dsc";
条件:
1.字符串的长度始终为9个字符。
2.字符串不区分大小写。
最佳答案
static void Main(string[] args)
{
string test1 = "bc3231dsc";
string tes2 = "bc3462dsc";
string firstmatch = GetMatch(test1, tes2, false);
string lasttmatch = GetMatch(test1, tes2, true);
string center1 = test1.Substring(firstmatch.Length, test1.Length -(firstmatch.Length + lasttmatch.Length)) ;
string center2 = test2.Substring(firstmatch.Length, test1.Length -(firstmatch.Length + lasttmatch.Length)) ;
}
public static string GetMatch(string fist, string second, bool isReverse)
{
if (isReverse)
{
fist = ReverseString(fist);
second = ReverseString(second);
}
StringBuilder builder = new StringBuilder();
char[] ar1 = fist.ToArray();
for (int i = 0; i < ar1.Length; i++)
{
if (fist.Length > i + 1 && ar1[i].Equals(second[i]))
{
builder.Append(ar1[i]);
}
else
{
break;
}
}
if (isReverse)
{
return ReverseString(builder.ToString());
}
return builder.ToString();
}
public static string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
关于c# - 比较两个字符串中的字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7879636/