开发者

Java and substring

开发者 https://www.devze.com 2022-12-16 05:48 出处:网络
I need something simmilar to \"awk { print $1 }\", but for java. I have a string, similar to th开发者_C百科is:

I need something simmilar to "awk { print $1 }", but for java. I have a string, similar to th开发者_C百科is:

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];


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


String example = "word1 word2 word3 word4 word5 word6";
int indexOf = example.indexOf(" ");
String firstWord = example.substring(0, indexOf == -1? example.length: indexOf);
0

精彩评论

暂无评论...
验证码 换一张
取 消