【发布时间】:2022-07-05 23:29:13
【问题描述】:
【问题讨论】:
-
@OlivierJacot-Descombes 这是一个不会离开网站的链接:meta.stackoverflow.com/questions/251361/…
标签: c#
【问题讨论】:
标签: c#
Words.All(s=>s.Length==Words.Length)
使用检查所有字符串是否与第一个字符串的长度相同。 Nite 不适用于空数组
【讨论】:
Words[0].Length
您发布的代码将比较每个字符串的长度(以字符为单位)与整个数组的长度(以元素数量为单位),因为myArray.Length 给出了数组中的元素数量,而"string".Length给出字符数。您要做的过程是记录第一个字符串的长度,并将该长度与数组中的每个字符串进行比较,看看是否有任何长度不同的字符串。
在 C# 中:
string[] myArray = new String[] {"four", "char", "word"};
boolean allSameLength = true;
int firstLen = myArray[0].Length;
for (int i = 1; i < myArray.Length; i++)
{
if (myArray[i] != firstLen)
{
allSameLength = false;
}
}
此功能封装在 pm100 的响应中。 .All() 将确定数组中的任何元素是否通过逻辑测试,lambda operator 用于通过逻辑测试以应用 (s.length==Words[0].Length)。
【讨论】:
myArray[i].Length != firstLen
简单方法:
public static bool CompareSetrings(string[] words)
{
// Return false is the array is empty
if(words.Length == 0)
return false;
// The var will hold the length of the first string
int initialLength = 0;
// Iterating trough string array
for(int i = 0; i < words.Length; i++)
{
// Initialize on first iteration for further comparaison with the first string length
if(i == 0) initialLength = words[i].Length;
if (initialLength != words[i].Length)
{
// If the length is different, return false
return false;
}
}
return true;
}
【讨论】:
int initialLength = words[0].Length 并删除每个循环中的比较?