C#-如何检查给定的 2 个包含 2 个或 3 个单词的字符串是否具有单个字母并比较 2 个字符串的第一个字母是否相同以及 return 是真还是假?
C#- How to check whether given 2 strings with 2 or 3 words has single letter and compare first letter of 2 strings are same and return true or false?
bool isMatch = false;
var string1list = string1.Trim().ToLower().Split(" ").ToList();
var string2list = string2.Trim().ToLower().Split(" ").ToList();
if (string1List.Count == string2List.Count)
{
int tokenCount = string1List.Count;
for (int i = 0; i < tokenCount; i++)
{
if (string1List[i].Length == 1 || string2List[i].Length == 1)
{
try
{
if (string1List[i][0] == string2List[i][0])
{
isMatch = true;
continue;
}
else
{
isMatch = false;
break;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
return isMatch;
示例:
string string1 = "John M Marshal";
string string2 = "John M Marshal";
首先要检查2个字符串是否有单字,如果有则进行比较
在比较中,它应该比较两个字符串中每个单词的首字母,如果相同则应该 return true 否则为 false。
给你:
string string1 = "John M Marshal";
string string2 = "John M Marshal";
string[] split1 = string1.Split(' ');
string[] split2 = string2.Split(' ');
bool result =
split1.Any(x => x.Length == 1)
&& split2.Any(x => x.Length == 1)
&& split1.Length == split2.Length
&& split1.Zip(split2, (s1, s2) => s1[0] == s2[0]).All(x => x);
这给了我 true
。
bool isMatch = false;
var string1list = string1.Trim().ToLower().Split(" ").ToList();
var string2list = string2.Trim().ToLower().Split(" ").ToList();
if (string1List.Count == string2List.Count)
{
int tokenCount = string1List.Count;
for (int i = 0; i < tokenCount; i++)
{
if (string1List[i].Length == 1 || string2List[i].Length == 1)
{
try
{
if (string1List[i][0] == string2List[i][0])
{
isMatch = true;
continue;
}
else
{
isMatch = false;
break;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
return isMatch;
示例:
string string1 = "John M Marshal";
string string2 = "John M Marshal";
首先要检查2个字符串是否有单字,如果有则进行比较
在比较中,它应该比较两个字符串中每个单词的首字母,如果相同则应该 return true 否则为 false。
给你:
string string1 = "John M Marshal";
string string2 = "John M Marshal";
string[] split1 = string1.Split(' ');
string[] split2 = string2.Split(' ');
bool result =
split1.Any(x => x.Length == 1)
&& split2.Any(x => x.Length == 1)
&& split1.Length == split2.Length
&& split1.Zip(split2, (s1, s2) => s1[0] == s2[0]).All(x => x);
这给了我 true
。