简体   繁体   English

如何检查数组中的所有字符串是否长度相同c#

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

for instance,例如,

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

how do i know if all string's length in this array are equal (without using 'for' or 'foreach') .我怎么知道这个数组中所有字符串的长度是否相等(不使用'for'或'foreach')

另一种解决方案:

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

Here is a solution without using for(each) as requested:这是一个不按要求使用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;

Here is another solution that does not use for(each) and does not try to cheat by using a different type of loop (like while ):这是另一个不使用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);

Most ridiculous use of recursion?最荒谬的递归使用?

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