简体   繁体   中英

Checking if all strings have equal length in a String array in Java

I am trying to solve a question in which I am given a String array of words and I have to check whether they have all same length or not. For instance if am given the array {"apple","purple","lemon"} then my method should return true , and when I am given the array {"red","blue"} , it should return false .

This is what I did so far but it is not working. I appreciate any help.

public static boolean allEqualLength(String[] myArray){
    int i;
    for(i=0;i<myArray.length;i++){
        if(myArray[i]!=myArray[i+1])
            return false;
        }    
    return true,
}

All items having the same length is equivalent to saying all items must have the same length as the first item:

public static boolean allEqualLength(String[] myArray) {
    // zero items => "all" items have same length:
    if (myArray.length == 0) return true;
    final int expectedLength = myArray[0].length();
    for(int i = 0; i < myArray.length; ++i) {
        if(myArray[i].length() != expectedLength)
            return false;
    }    
    return true,
}

But your original solution was not that far off. You just need to make sure not to exceed the array's bounds and to compare the string lengths, not the strings themselves:

public static boolean allEqualLength(String[] myArray) {
         for(int i=0; i < myArray.length - 1; i++) { // -1 to not exceed bounds
             if(myArray[i].length() != myArray[i+1].length()) // compare length, not memory addresses
                return false;
         }    
         return true,
}

I world do something like that:

public static boolean allEqualLength(String[] myArray) {

     int strLength = myArray[0].length();

    for (String str :
            myArray) {
        if (str.length() != strLength)
            return false;
    }
     return true;
}

Like that you can avoid any indexing problems in your loop.

You are trying to compare the strings themselves. You should compare the length only.

myArray[i].length() != myArray[i + 1].length()

By the way, this will throw an ArrayIndexOutOfBoundsException , because you are trying to access index myArray[myArray.length] . Change the for loop to

for (int i = 0; i < myArray.length - 1; i++) {
    if (myArray[i].length() != myArray[i + 1].length()) {
        return false;
    }
}

Also make sure you return true if the array length is 0 or 1, because the loop can't handle those.

For example you have array with length 4, you have the positions 0,1,2,3 so in your code you run with: myArray[i]!=myArray[i+1] so on the last run you check the positions: 3 and 4 and you will get ArrayIndexOutOfBoundsException , you need to change to: length-1 on the loop condition like this:

public static boolean allEqualLength(String[] myArray){
    int i;
    for(i=0;i<myArray.length -1;i++){
        if(myArray[i].length() != myArray[i+1].length())
            return false;
        }    
    return true,
}

If you run on myArray.length,the positions that check:

0--1
1--2
2--3
3--4 // ERROR !!! ArrayIndexOutOfBoundsException !!

If you run on myArray.length-1,the positions that check:

0--1
1--2
2--3 -OK !!!

So on this way if you run the array with: myArray.length-1 , you will not get ArrayIndexOutOfBoundsException .

First things first you are not checking element lengths other issue is your for loop would try to access array index out of bounds since you have i+1, last element is already being checked that way, considering that you just need for until myArray.length - 1.

Using your code it would look something like this:

public static boolean allEqualLength(String[] myArray) {
    for (int i = 0; i < myArray.length - 1; i++) {
        if (myArray[i].length() != myArray[i + 1].length())
            return false;
    }
    return true;
}

If performance is not an issue and you will not use it in 1 million strings or something, in addition to all these answers, here is an one liner:

boolean allStringsEqualLength = Stream.of(array)
        .map(String::length).distinct().count() == 1;

The idea is to map each string to its length. So if distinct() stream contains only one value, that means all strings had the same length.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM