Click here to Skip to main content
15,885,952 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I am facing this small issue on the split method in java. Not sure this is a known one or not.. please help.

Java
String tmp = "Hello I      am fine   ";
String str[] = tmp.split(" ");
System.out.println("STR[0] => " + str[0]);
		
String tmp1 = "  Hello I      am fine   ";
String str1[] = tmp1.split(" ");
System.out.println("STR1[0] => " + str1[0]);


Output as below:

VB
STR[0] => Hello
STR1[0] =>


As you can see, if there is a space before "hello" word, this is happening.. is there is any workaround for this? I know that split takes regex as argument, but still there has to be a way to skip the first empty space if it exists before the word ? right?

Thanks in advance.
Posted

1 solution

Try triming the string before splitting. Trmming will remove all the leading and trailing whitespaces.
Java
String tmp = "Hello I      am fine   ";
String str[] = tmp.trim().split(" ");
System.out.println("STR[0] => " + str[0]);

String tmp1 = "  Hello I      am fine   ";
String str1[] = tmp1.trim().split(" ");
System.out.println("STR1[0] => " + str1[0]);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900