Length of an array that was initialized using a split string?

时间:2015-10-30 21:54:23

标签: java arrays string

I have the following code to split a String of a list of words separated by spaces. The string is split and used to populate the array. If I use the .length method, will it return the amount of split strings? As in, would it be similar to the String.length method that counts the amount of characters and returns that value?

I want to have the program increment the array position by one each time it's run, but I want it to reset to 0 if it already used the last word, so it circles back and starts with the first word again.

Would this bit of code reset the word position to 0 when it has already used the last word in the array?

String wordsList[] = words.split(" ");
        this.currentWord = wordsList[wordPos];
        if(wordPos < wordsList.length)
            wordPos++;
        else
            wordPos = 0;

2 个答案:

答案 0 :(得分:0)

If you use array.length on an array doesn't it tell you what the length is? The answer is yes. Also, the .length is a property and not a method.
Take a look at this going over the .length property with a bit more detail. Cheers.

答案 1 :(得分:0)

If I understand correctly, It sounds like you want to use a for loop like this?:

String words = "Blah blarg bloob"
String wordsList[] = words.split(" ");
String currentWord = "";
for (int i = 0; i < wordsList.length; i++){
    if (currentWord !=null && currentWord.equals(wordsList[i])) {i = 0;}
    currentWord = wordsList[i];
}