簡體   English   中英

如何檢查數組中的所有字符串是否長度相同c#

[英]How to check if all strings in array are the same length c#

例如,

string[] text=new string[] {"dsasaffasfasfafsa", "siuuuuu", "ewqewqeqeqewqeq"};

我怎么知道這個數組中所有字符串的長度是否相等(不使用'for'或'foreach')

另一種解決方案:

bool allSameLength = !text.Any(t => t.Length != text[0].Length));

這是一個不按要求使用for(each)的解決方案:

string[] text = new string[] {"dsasaffasfasfafsa", "siuuuuu", "ewqewqeqeqewqeq"};
int index = 0, firstLength = -1;
bool allSameLength = true;
while(index < text.Length)
{
    int length = (text[index] + '\0').IndexOf('\0');
    firstLength = (index == 0) ? length : firstLength;
    allSameLength &= (length != firstLength) ;
    index += 1;
}

return allSameLength;

這是另一個不使用for(each)並且不嘗試通過使用不同類型的循環(如while )來作弊的解決方案:

    string[] text = new string[] {"dsasaffasfasfafsa", "siuuuuu", "ewqewqeqeqewqeq"};

    List<string> texts = new List<string>();
    texts.Add(null);
    texts.AddRange(text);
    texts.Add(null);
    
    bool CheckSameLength(int index)
      => (texts[index + 1] == null) ? true
       : texts[index] == null ? CheckSameLength(1)
       : texts[index].Length == texts[index + 1].Length ? CheckSameLength(index + 1)              
       : false;
      
    return CheckSameLength(texts, 0);

最荒謬的遞歸使用?

public class Program {
  
  public static void Main() {
    string[] text = new string[] {"dsasaffasfasfafsa", "siuuuuu", "ewqewqeqeqewqeq"};
    Console.WriteLine(AllLengthsEqual(text));
  }

  public static bool AllLengthsEqual(string[] strArr) {
    return strArr == null ? true : (strArr.Length < 2 ? true : AllLengthsEqual(strArr, 0));
  }

  private static bool AllLengthsEqual(string[] strArr, int index) {
    return AllLengthsEqual(strArr, index + 1, strArr[index] != null ? strArr[index].Length : -1);
  }

  private static bool AllLengthsEqual(string[] strArr, int index, int prevLength) {    
    if (index < strArr.Length) {
      int thisLength = strArr[index] != null ? strArr[index].Length : -1;
      return (thisLength == prevLength) && AllLengthsEqual(strArr, index + 1, thisLength);
    }
    else 
      return true;    
  }
  
}

暫無
暫無

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

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