Hello, I need something simmilar to "awk { print $1 }", but for java. I have a string, similar to this:
word1 word2 word3 word4 word5 word6
How, can I substring first word, from every line?
Hello, I need something simmilar to "awk { print $1 }", but for java. I have a string, similar to this:
word1 word2 word3 word4 word5 word6
How, can I substring first word, from every line?
String example = "word1 word2 word3 word4 word5 word6";
String firstWord = example.split(" ", 2)[0];
String example = "word1 word2 word3 word4 word5 word6";
int indexOf = example.indexOf(" ");
String firstWord = example.substring(0, indexOf == -1? example.length: indexOf);
Here's a solution that doesn't fail if there is only one word on the line. I assume that you have already stripped the new line characters, and that space is the only allowed separator:
for (String line: lines)
{
int index = line.indexOf(' ');
String firstWord;
if (index >= 0)
{
firstWord = line.substring(0, index);
}
else
{
firstWord = line;
}
System.out.println(firstWord);
}