Signup/Sign In

Java String to Array Conversion

In this post, we are going to convert a string to an array using Java code. The string is a sequence of characters and a class in Java while array is an index-based data structure used to store similar types of elements.

Here, we are using the split() method of String class that is used to split a string based on specified delimiter and returns an array.

This is a common day to day task of programming where we have some textual string and want to process it as an array so we need to explicitly convert it to the array.

The conversion is simply easy and does not require many lines of code. We just need to use the split() method, see the examples below.

Time for an Example:

Let's take an example to understand the conversion of string to string array. Here, we split array based on space delimiter and get an array as a result.

public class Main {
	public static void main(String[] args){
		String msg = "StudyTonight.com is a technical portal";
		System.out.println(msg);
		// string to string array
		String[] arg = msg.split(" ");
		for (int i = 0; i < arg.length; i++) {
			System.out.println(arg[i]);
		}
	}
}


StudyTonight.com is a technical portal
StudyTonight.com
is
a
technical
portal

Time for another Example:

Suppose, we have a URL string and want to get it as an array then we can split the URL by specifying the separator like:'/' as in the below example. It returns the URL string as a string array.

public class Main {
	public static void main(String[] args){
		String msg = "StudyTonight.com/tutorial/java/string";
		System.out.println(msg);
		// string to string array
		String[] arg = msg.split("/");
		for (int i = 0; i < arg.length; i++) {
			System.out.println(arg[i]);
		}
	}
}


StudyTonight.com/tutorial/java/string
StudyTonight.com
tutorial
java
string



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.