How to break lines in java

I have two types of strings. One of them is "abcdEfgh" and "abcd efgh" . This means that the first line has an uppercase letter, and the second line has a space. So now, how can I check these two lines of the template in java and make two lines.

 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 a solution. Thanks

+5
source share
3 answers

You can split using regex \\s|(?=[AZ])

  • \\s is a case with a space.
  • (?=[AZ]) - a positive result. It finds an uppercase letter, but retains the delimiter when split.

.

 String givenString; String split[] = givenString.split("\\s|(?=[AZ])"); 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 
+5
source

You need to combine the two conditions using the OR | . You already realized that dividing the space is simple. "In the uppercase example, Java answers : split the string when the uppercase letter is found

Example

 String one = "abcdEfgh"; String two = "abcd efgh"; System.out.println(Arrays.toString(one.split(" |(?=\\p{Upper})"))); System.out.println(Arrays.toString(two.split(" |(?=\\p{Upper})"))); 

Output

 [abcd, Efgh] [abcd, efgh] 
+2
source

Keep it simple, find a space in givenString instead of case sensitive matches

 if(givenString.indexOf(" ") != -1){ System.out.println( "The string has spaces"); }else{ System.out.println( "The string has NO spaces"); } 
0
source

Source: https://habr.com/ru/post/1264979/


All Articles