Categories
java

Split String in java using delimiter

Split String in java using delimiter

In this tutorial we will learn how to split a string in java using delimiter
we will use split method to split the string variable

Synatx

s.split(" "); // here delimiter is space
s.split("-"); // here - is space
s.split("_"); // here _ is space

Example using space

public class SplitStringExample {

	public static void main(String[] args) {
		String s = "this is an example";
		// In below line we used space as a delimiter
		String[] split = s.split(" ");
		// we will get the splited string as array
		// In below line we using for loop to print each array value
		for (int i = 0; i < split.length; i++) {
			System.out.println(split[i]);
		}
	}
}

Output

this
is
an
example

Example using –

public class SplitStringExample {

	public static void main(String[] args) {

		String s = "google-yahoo";
		// In below line we used space as a delimiter
		String[] split = s.split("-");
		// we will get the splited string as array
		//In below line we using for loop to print each array value
		for (int i = 0; i < split.length; i++) {
			System.out.println(split[i]);
		}

	}

}

Output

google
yahoo
Reference

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

Leave a Reply

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