简体   繁体   English

检查 Java 中的字符串数组中的所有字符串是否具有相同的长度

[英]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 .例如,如果给定数组{"apple","purple","lemon"}那么我的方法应该返回true ,当给定数组{"red","blue"}时,它应该返回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] .顺便说一句,这将引发ArrayIndexOutOfBoundsException ,因为您正在尝试访问索引myArray[myArray.length] Change the for loop to将 for 循环更改为

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.如果数组长度为 0 或 1,还要确保返回true ,因为循环无法处理这些。

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:例如,您有长度为 4 的数组,位置为0,1,2,3 ,因此在您运行的代码中: myArray[i]!=myArray[i+1]所以在最后一次运行时检查位置: 3和4,你会得到ArrayIndexOutOfBoundsException ,你需要在循环条件上更改为: length-1 ,如下所示:

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:如果你在 myArray.length 上运行,检查的位置:

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

If you run on myArray.length-1,the positions that check:如果您在 myArray.length-1 上运行,检查的位置:

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 .因此,如果您使用以下方式运行数组: myArray.length-1 ,您将不会得到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.首先你没有检查元素长度其他问题是你的for循环会尝试访问数组索引越界,因为你有i + 1,最后一个元素已经被检查过,考虑到你只需要直到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:如果性能不是问题并且您不会在 100 万个字符串或其他东西中使用它,那么除了所有这些答案之外,这里有一个单行:

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

The idea is to map each string to its length.这个想法是 map 每个字符串到它的长度。 So if distinct() stream contains only one value, that means all strings had the same length.因此,如果distinct() stream 仅包含一个值,则意味着所有字符串的长度相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中检查字符串和字符串数组 - Checking String and an Array of Strings in Java 检查java中字符串数组的大小或长度 - Checking the size or length of a string array in java Java:检查字符串是否等于字符串 - Java: Checking if a String is equal to a String 如何通过检查长度并比较Java中的文本来从数组中删除String? - How to remove String from an array by checking length and comparing text in Java? 将字符串拆分为等长的子字符串 - Splitting a string into sub-strings of equal length 如何使数组的长度等于字符串的长度? - How to get the length of the array equal to the length of a string? 如何打印“ ALL”具有存储在array(JAVA)中的最长length()的最长字符串的问题 - Problem with how to print “ALL” the longest string which have SAME longest length() that stored in array(JAVA) 给定一个字符串数组,单词,则返回该数组,将所有长度均等的字符串替换为空字符串 - Given an array of Strings, words, return that array with all Strings of an even length replaced with an empty string Java:将按字符串长度排序的字符串数组拆分为多个 arrays 按字符串长度 - Java: Split array of strings sorted by string length into several arrays by string length Java - 检查变量是否等于任何数组元素 - Java - Checking if a variable is equal to any of the array elements
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM