Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split Strings in java

Tags:

java

string

I have two types of Strings. One is "abcdEfgh" and "abcd efgh". That means first String is having upper case letter in between and second string is having white space. So now how do I check these two pattern string in java and make two strings.

String givenString;

if (givenString.equals("abcdEfgh")) {
   String str1 = abcd;
   String str2 = Efgh;
} else (givenString.equals("abcd efgh") {
   String str1 = abcd;
   String str2 = efgh;
}

Please provide the solution Thanks

like image 693
Pratibha Patil Avatar asked Mar 03 '17 09:03

Pratibha Patil


1 Answers

You can split using regex \\s|(?=[A-Z])

  1. \\s is to deal with case of whitespace.
  2. (?=[A-Z])is positive lookahead. It finds capital letter but keeps the delimiter while splitting.

.

String givenString;
String split[] = givenString.split("\\s|(?=[A-Z])");
String str1 = split[0];
String str2 = split[1];

for both cases

Test case 1

//case 1
givenString = "abcdEfgh";
str1 = abcd
str2 = Efgh

Test case 2

//case 2
givenString = "abcd efgh";
str1 = abcd
str2 = efgh
like image 85
Raman Sahasi Avatar answered Sep 22 '22 16:09

Raman Sahasi