SSJX.CO.UK
Content

Java String Split

String Split

The String split method breaks a string using a particular separator and puts the result into an array.

String Split Example

Splitting a String

The code below will use the split method and fill the 'num' array with the values 10,20,30 and 40. The String txt is split on the comma','. Note that the array will contain four String items, not numbers / integers.

String txt="10,20,30,40";
String[] num=txt.split(",");

Converting a String to a number

Our array is full of Strings. As we want to add them up, they will need to be converted to numbers. Integer.parseInt(age) can be used to do this, if it fails it will trigger an exception. E.g.

try{
	int num=Integer.parseInt("10");
}catch(Exception e){
	System.out.println("Hmmm... That did not work");		
}

In the full program below, the String to be split has the letter 'b' in it so you can see what happens if parseInt() fails.

Full Program

With the Java JDK installed, from a command line:

class SplitTest{
	public static void main(String[] args){
		// The 'b' is not a number and is used as a test to trigger the exception	
		String txt="10,20,b,40";
		
		String[] num=txt.split(",");
		
		int total=0;
		
		System.out.println("Line:\t"+txt);
		
		for(var n:num){
			try{
				int tmp=Integer.parseInt(n);
				total=total+tmp;
			}catch(Exception e){
				System.out.println(n+" is not a number.");
			}
		}
		
		// The '\t' inserts a tab
		System.out.println("Total:\t"+total);
	}
}

Created (06/05/2025)
Update (06/05/2025)