Java Parse String Sample

If you need to do String Parsing in Java, there is a very nice method that can be used. Parsing is the division of text into tokens or pieces. The split() method of the String class splits a string based on the regular expression used and returns an array

The string parse sample code below defines a string, calls the split() method to split the string into tokens based on our delimiter (one space). The split() method returns an array, which we then use an enhanced for loop to print out each token.


Java Parse String Source Code

package com.jcd.java.tutorials;

public class JavaParseStringSample {


	public static void main(String[] args) {
	
		//Let's define a string to parse
		String jcdDummyString = "Java Code Depot Parse String Sample";
		
		//Split the string using a space as the delimiter
		String[] jcdArray = jcdDummyString.split(" ");
		
		//Enhanced loop to parse through each item in array
		for(String eachToken : jcdArray) {
			
			System.out.println("eachToken="+eachToken);
		}
	}

}


Java Parse String Output

eachToken=Java
eachToken=Code
eachToken=Depot
eachToken=Parse
eachToken=String
eachToken=Sample


Add a Comment

Your email address will not be published. Required fields are marked *