String

String split method

This is an example of how to split a String. The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Splitting a String implies that you should:

  • Create a new String.
  • Use the split(String regex) API method of String. This method splits this string around matches of the given regular expression.
  • Use split(String regex, int limit) API method of String. This method splits this string around matches of the given regular expression.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

public class StringSplitMethod {
	
	public static void main(String[] args) {
		
		String s = "Java Code Geeks";
		
		String[] temp;
		String delimiter;
		 
		delimiter = " ";
		temp = s.split(delimiter);
		
		for (int i =0; i < temp.length ; i++)
			System.out.println(temp[i]);
		
		System.out.println();
		
		temp = s.split(delimiter,2);
		
		for (int i =0; i < temp.length ; i++)
			System.out.println(temp[i]);
		
		System.out.println();
		
		s = "Java.Code.Geeks";
		delimiter = "\.";
		temp = s.split(delimiter);
		
		for (int i =0; i < temp.length ; i++)
			System.out.println(temp[i]);
		 
	}

}

Output:

Java
Code
Geeks

Java
Code Geeks

Java
Code
Geeks

 
This was an example of how to split a String in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button