我有两个字符串
一个是
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