簡體   English   中英

如何測試數組中的所有字符串是否具有相同的長度

[英]How to test if all strings in an array are of the same length

我有一個字符串數組。
如何測試此數組中的所有元素是否具有相同的長度?

這是我到目前為止所擁有的:

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;
}

您發布的代碼會將每個字符串的長度(以字符為單位)與整個數組的長度(以元素數計)進行比較,因為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].Length != firstLen)
   {
      allSameLength = false;
      break;
   }
}

此功能封裝在 pm100 的響應中。 .All()將確定數組中的元素是否通過邏輯測試,並且lambda 運算符用於通過邏輯測試以應用( s.length==Words[0].Length )。

使用 Linq 非常簡單:

public bool CompareStringLength(string[] words)
{
    return words.Select(w => w.Length).Distinct().Count() == 1;
}

一個更有效的版本(當遇到兩個不同的長度時停止):

public bool CompareStringLength(string[] words)
{
    return words.Select(w => w.Length)
                .Distinct()
                .Take(2)
                .Count() == 1;
}

注意:問題中未提供數組為空時的預期結果。
如果在這種情況下需要true ,請使用Count() <= 1

簡單方法:

    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 = words[0].Length;

        // Iterating trough string array
        for(int i = 0; i < words.Length; i++)
        {
            // If the length is different, return false
            if (initialLength != words[i].Length)
                return false; 
        }
        return true;
    }

嘗試這個

public static bool CompareSetrings(string[] words)
{
    var len = words[0].Length;
    foreach (string word in words)
    if(word.Length != len) return false;
    return true;
}

函數接受一個字符串數組。 如果數組為null或數組中只有 0 或 1 個單詞,它將返回 true。 如果有多個單詞,它會獲取數組中第一個單詞的長度,然后使用 LINQ 的All方法通過將每個單詞的長度與第一個單詞的長度進行比較來檢查數組中的所有字符串是否具有相同的長度 ( firstWordLength )。 它跳過( Skip(1) )數組中的第一個單詞,因為我們使用第一個單詞的長度,因此我們刪除了冗余檢查。

public static bool CheckAllStringLengthsAreEqual(string[] words)
{
    if (words is null || words.Length <= 1)
    {
        return true;
    }

    var firstWordLength = words[0].Length;

    return words.Skip(1).All(x => x.Length == firstWordLength);
}
Words.All(s=>s.Length==Words.Length)

使用檢查所有字符串是否與第一個字符串的長度相同。 Nite 不適用於空數組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM