如何测试数组中的所有字符串是否具有相同的长度
我有一系列的字符串。
如何测试此数组中的所有元素是否具有相同的长度?
这是我到目前为止所拥有的:
public static bool ComparingStrings(string[] words)
{
bool result = false;
for (int i = 0; i < words.Length; i++)
{
string s = words[i];
if (s.Length == words.Length)
{
result = true;
}
else
{
result = false;
}
}
return result;
}
I have an array of strings.
How to test if all elements in this array have the same length ?
Here is what I have so far :
public static bool ComparingStrings(string[] words)
{
bool result = false;
for (int i = 0; i < words.Length; i++)
{
string s = words[i];
if (s.Length == words.Length)
{
result = true;
}
else
{
result = false;
}
}
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用检查所有字符串的长度与第一个字符串相同。午夜不适用于空数组
Use check if all strings have same length as first one. Nite will not work on empty array
您发布的代码将比较每个字符串的长度(以字符为单位)与整体数组的长度(元素数),因为
myArray.length.length
提供了数组中的元素数量,和“ String” .length
给出字符的数量。您必须执行的过程是记录第一个字符串的长度,并将该长度与数组中的每个字符串进行比较,以查看是否有任何不相同的长度。在C#中:
此功能封装在PM100的响应中。 将确定数组中的元素是否通过逻辑测试,而 lambda operator测试要应用(
s.length ==单词[0] .length
)。The code you have posted will compare the length of each string (in characters) to the length of the overall array (in number of elements), since
myArray.Length
givees the number of elements in an array, and"string".Length
gives the number of characters. The process that you have to do is record the length of the first string, and compare that length to every string in the array to see if there are any which are not the same length.In C#:
This functionality is encapsulated in pm100's response. .All() will determine whether ever element in an array passes a logical test, and the lambda operator is used to pass the logical test to apply (
s.length==Words[0].Length
).使用linq非常简单:
一个更高效的版本(遇到两个不同的长度时停止):
nota:问题中未提供数组为空时的预期结果。
如果您需要
true
在这种情况下,请使用count()&lt; = 1
;Using Linq it's pretty straightforward:
A more efficient version (that stop when two distinct length are encountered):
Nota: The expected result when the array is empty is not provided in the question.
If you need
true
in this case, useCount() <= 1
;简单方法:
Simple method:
尝试一下
try this
功能接受字符串数组。如果数组为
null
,或者数组中只有0或1个字,它将返回true。如果有多个单词,它会抓住数组中的第一个单词的长度,然后使用Linq的所有
方法来检查数组中的所有字符串是否具有将每个单词的长度与每个单词的长度与第一个单词的长度(firstWordLength
)。它跳过(跳过(1)
)数组中的第一个单词,因为我们使用了第一个单词的长度,因此我们删除了冗余检查。Function accepts a string array. It will return true if the array is
null
or there is only 0 or 1 word in the array. If there is more than one word, it grabs the length of the first word in the array then uses LINQ'sAll
method to check if all the strings in the array have the same length by comparing each word's length to the length of the first word (firstWordLength
). It skips (Skip(1)
) the first word in the array because we use the first word's length so we remove a redundant check.