How to Extract Words from a String in Java


In this example we will show how to split a String into multiple String objects in Java.

Source Code

1)

package com.beginner.examples;

import java.util.StringTokenizer;

public class SeparateWordsExamples {

	
	public static void main(String[] args) {
	
		String names = "Kelly Easter Addison Fred";
		
		//create StringTokenizer object
		StringTokenizer tokenizerNames = new StringTokenizer(names);
		
		System.out.println("Names:");
		
		//循环获得每个单词
		while(tokenizerNames.hasMoreTokens())
		{
			String name = tokenizerNames.nextToken();
			
			System.out.println(name);
		}

	}

}

Output:

Names:
Kelly
Easter
Addison
Fred

2)

package com.beginner.examples;

import java.util.Arrays;

public class SeparateWordsExample2 {

	public static void main(String[] args) {

		String names = "Kelly  Easter   Addison   Fred";

		// Use regular to cut strings
		//s for space, + for one or more
		String[] namesArr = names.split("s+");

		// Use the toString() method in the Arrays utility class 
		//to print the array
		
		System.out.println(Arrays.toString(namesArr));

	}

}

Output:

[Kelly, Easter, Addison, Fred]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments