0

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?

3 Answers 3

9
String example = "word1 word2 word3 word4 word5 word6";
String firstWord = example.split(" ", 2)[0];
Sign up to request clarification or add additional context in comments.

4 Comments

Just be sure that list isn't empty as you go through the data. :)
Using split(" ", 1) would be better. It reduces the number of unnecessary strings created to only one unnecessary string instead of lots.
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 java.sun.com/j2se/1.4.2/docs/api/java/lang/…
I fixed it for you, seeing as it was my fault!
4

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);
    }

3 Comments

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.
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.
done, thanks (I was just answering the "here is a solution that doesn't fail...")
3
String example = "word1 word2 word3 word4 word5 word6";
int indexOf = example.indexOf(" ");
String firstWord = example.substring(0, indexOf == -1? example.length: indexOf);

2 Comments

This fails if the line only has one word.
Now it'll give you an empty string if you've only got one word.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.