java 在java中修剪字符串以获得第二个单词,第三个单词和第四个单词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25588800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:17:15  来源:igfitidea点击:

Trim a string to get second word, third word and fourth word in java?

javaregexstring

提问by jkclaro

I have two Strings

我有两个字符串

One is

一个是

String s1 = "I have 1000 dollars";

String s1 = "我有 1000 美元";

Second is

其次是

String s2 = "I want my pet";

String s2 = "我想要我的宠物";

I need to ONLY get "have" , "1000", "dollars" in s1. Similarly, I need to ONLY get "want", "my" and "pet" in s2.

我只需要在 s1 中获得“拥有”、“1000”、“美元”。同样,我只需要在 s2 中获取“想要”、“我的”和“宠物”。

I know how to get the "I" using the code

我知道如何使用代码获得“我”

String newS1 = s.substring(0, s.indexOf(" "));

String newS1 = s.substring(0, s.indexOf(" "));

Is there a way I can achieve this using substring?

有没有办法使用子字符串来实现这一点?

采纳答案by allenwoot

String trimFirstWord(String s) {
    return s.contains(" ") ? s.substring(s.indexOf(' ')).trim() : "";
}

回答by Kick Buttowski

If you always want to use second ,third ,and fourth words in any strings you have, I would recommend you to use split functions.

如果您总是想在任何字符串中使用第二个、第三个和第四个单词,我建议您使用拆分函数。

Code:

代码:

    String s1 = "I have 1000 dollars";
    String[] sp = s1.split(" ");
    System.out.println("second word is " + sp[1]);
    System.out.println("third word is " + sp[2]);
    System.out.println("Fourth words is " +sp[3]);

Output:

输出:

second word is have
third word is 1000
fourth word is dollars

回答by Avinash Raj

You could try the below rgex to get the second, third, fourth words.

您可以尝试使用下面的 rgex 来获取第二、第三、第四个单词。

^\S+\s*(\S+)\s*(\S+)\s*(\S+).*$

DEMO

演示

Group index 1 contains the first word, index 2 contains the 2nd word and index 3 contains the third word.

组索引 1 包含第一个单词,索引 2 包含第二个单词,索引 3 包含第三个单词。

Pattern regex = Pattern.compile("^\S+\s*(\S+)\s*(\S+)\s*(\S+).*$");
 Matcher matcher = regex.matcher("I have 1000 dollars");
 while(matcher.find()){
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
        System.out.println(matcher.group(3));

}

Output:

输出:

have
1000
dollars