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

标签 java regex string

<分区>

我有两个字符串

一个是

String s1 = "I have 1000 dollars";

第二个是

String s2 = "I want my pet";

我只需要在 s1 中得到“have”、“1000”、“dollars”。 同样,我只需要在 s2 中得到“want”、“my”和“pet”。

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

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

有没有一种方法可以使用子字符串实现这一点?

最佳答案

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

代码:

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

输出:

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

关于java - 修剪字符串以获得java中的第二个单词,第三个单词和第四个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25588800/

相关文章:

java - J2EE/EJB + 服务定位器 : is it safe to cache EJB Home lookup result?

java - requestparam 的 Spring 验证不起作用

mysql - 检测MySQL中的重复字符

c - 如何在 sprintf() 中获取追加模式

javascript - 将字符串中的各个字母设置为不同的颜色

java - @ElementCollection with Map<Entity, Embeddable> 其中 Entity 是 Embeddable 的字段

java - Java中数组初始值设定项中带有尾随逗号的数组

regex - 指定 'inverted' 范围的 sed 行号范围

regex - Mongo RegEx - 匹配所有类型的空格字符

c - 丢失的字母去哪儿了?