I have the following sentence:
This is a text and we should print each word
I want to print each word from this sentence.
package lab2_3;
public class Main {
public static void main(String[] args) {
String s2 = "This is a text and we should print each word";
int i;
int j;
for (i = 0; i <= s2.length() - 1; i++){
if (s2.substring(i).startsWith(" ") || i == 0){
//here I search for the start of the sentence or " "
for (j = i + 1; j <= s2.length() - 1; j++){
if (s2.substring(j).startsWith(" ") || j == s2.length() - 1) {
//here I search for the next " " or the end of the sentence
System.out.println(s2.substring(i, j));
//printing
i = j;
//i=j because the next search must be done from where we left
}
}
}
}
}
}
Output:
This
is
a
text
and
we
should
print
each
wor
As you can see it almost works, but the letter d is missing from the last word. A possible solution is to add " " at the end and it will work, but I don't want to do that.
Can you please tell me where it is my mistake and how to fix it ?
Also, can you please provide a better solution for this.
You are overcomplicating things. String already have split(regexDelimiter)
method which accepts regex representing place on which you want to split.
Also enhanced for loop allows us to easily iterate over all elements of array or implementations of Iterable interface
for (String str : strArray){
//do something with str
}
Since Java 8 we have also String.join(delimiter, elements)
method which can create string representing element0[delimiter]element1[delimiter]..
.
So depending what you are looking for you may want to use
for (String word : s2.split(" ")){
System.out.println(word);
}
or
String inEachLine = String.join(System.lineSeparator(), s2.split(" "));
or maybe even simpler
String inEachLine = s2.replace(" ", System.lineSeparator());
Last example simply creates new String based on original one, This new string will have replaced each space with OS dependant line separator (like for Windows \r\n
).
You can also use additional class designed to help us reading data from string. This class is Scanner
. So in your case you could simply use
Scanner sc = new Scanner(s2);
while(sc.hasNext()){
System.out.println(sc.next());
}