flyingriefdy flyingriefdy - 3 months ago 7
Java Question

How does this CombineWords work/reads?

I'm new here and not very well versed with programming but am here to learn. I understand the simple loop for ( initialisation ; termination ; increment/decrements ) but not familiar with this one.

What does this initialisation and termination means in the for loop? How am I supposed to read this in literal?


  1. I pass through an argument say words[0] = I words,[1] = love, words[2]= apple

  2. sentence is assigned to ""

  3. w = words[0]

  4. sentence += w + " "

  5. w = words[1]

  6. sentence += w + " "

  7. w = words[2]

  8. ...

  9. terminate




public static String CombineWords(String[] words) {
String sentence = "";
for (String w : words) {
sentence += w + " ";
}
return sentence;
}



And here how does this delimiting "[ ]+" works? Say I pass "I love apple"

/**
* Parses a sentence into an array of words
* @param sentence the string sentence to parse
* @return an array of words (in the sentence)
*/
public static String[] GetWords(String sentence) {
return sentence.split("[ ]+");
}

Answer

If I understand correctly, you are asking about how the for loop works when declared like this:

for (String w : words) {

Basically, it iterates through the values in words, storing the current value of each iteration in the w variable.

So...

for (String w : words) {
    sentence += w + " ";
}

is like shorthand for

for (int i = 0; i < words.length; i++) {
    String w = words[i];
    sentence += w + " ";
}

In the background, it actually produces an Iterator and uses that, but that's not particularly important/interesting for a beginner.

Comments