tags:

views:

208

answers:

3

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?

+8  A: 
String example = "word1 word2 word3 word4 word5 word6";
String firstWord = example.split(" ", 2)[0];
Valentin Rocher
Just be sure that list isn't empty as you go through the data. :)
Arthur Thomas
Using split(" ", 1) would be better. It reduces the number of unnecessary strings created to only one unnecessary string instead of lots.
Mark Byers
corrected, thanks
Valentin Rocher
Oops should be 2 sorry. "The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times" from http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split%28java.lang.String,%20int%29
Mark Byers
I fixed it for you, seeing as it was my fault!
Mark Byers
+3  A: 
String example = "word1 word2 word3 word4 word5 word6";
int indexOf = example.indexOf(" ");
String firstWord = example.substring(0, indexOf == -1? example.length: indexOf);
Rubens Farias
This fails if the line only has one word.
Mark Byers
Now it'll give you an empty string if you've only got one word.
lins314159
ok, i fixed that
Rubens Farias
+4  A: 

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);
    }
Mark Byers
my solution doesn't fail if there is only one word...if split() cannot find the separator, it just keeps the string in the first element of the array.
Valentin Rocher
My solution doesn't fail either. Plus it uses much less memory and it doesn't scan the entire string. You should at least add the optimization I suggested as a comment to your answer.
Mark Byers
done, thanks (I was just answering the "here is a solution that doesn't fail...")
Valentin Rocher