Home > other >  How to check if all strings in array are the same length c#
How to check if all strings in array are the same length c#

Time:06-20

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').

CodePudding user response:

Compare with the first and use Skip All:

string first = text.FirstOrDefault();
bool allSameLength = text.Length <= 1 
    || text.Skip(1).All(t => (t?.Length ?? 0) == (first?.Length ?? 0));

CodePudding user response:

Here is a solution without using for(each) as requested:

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;

CodePudding user response:

Another solution:

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

CodePudding user response:

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):

    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);
  • Related