我想知道如何将一个较长的字符串拆分成一系列较短的子字符串或单词。
例如:
我想把句子“我想遛狗。”拆分成字符串:“I”,另一个字符串:“want”等。
我该怎么做?
我想把句子“我想遛狗。”拆分成字符串:“I”,另一个字符串:“want”等。
我该怎么做?
StringTokenizer separate = new StringTokenizer(s, " ");
String word = separate.nextToken();
System.out.println(word);
class test{
public static void main(String[] args){
StringTokenizer st= new StringTokenizer("I want to walk my dog.");
while (st.hasMoreTokens())
System.out.println(st.nextToken());
}
}
String sentence = "I want to walk my dog.";
Arrays.stream(sentence.split(" ")).forEach(System.out::println);
输出:
I
want
to
walk
my
dog.
或者
String sentence2 = "I want to walk my dog.";
Arrays.stream(sentence2.split(" ")).map(str -> str.replace(".", "")).forEach(System.out::println);
输出:
I
want
to
walk
my
dog
String[] str = s.split("[^a-zA-Z]+");