Little bird
Little bird

Reputation: 1088

How to split string in two parts

I'm retrieving Strings from the database and storing in into a String variable which is inside the for loop. Few Strings i'm retrieving are in the form of:

https://www.ppltalent.com/test/en/soln-computers-ltd

and few are in the form of

https://www.ppltalent.com/test/ja/aman-computers-ltd

I want split string into two substrings i.e https://www.ppltalent.com/test/en/soln-computers-ltd as https://www.ppltalent.com/test/en and /soln-computers-ltd.

It can easily be separated if i would have only /en.

String[] parts = stringPart.split("/en");
System.out.println("Divided String  : "+ parts[1]);

But in many of the strings it has /jr , /ch etc.

So how can I split them in two sub-strings?

Upvotes: 1

Views: 287

Answers (2)

aioobe
aioobe

Reputation: 421090

  • You could perhaps use the fact that /en and /ja are both preceeded by /test/. So, something like indexOf("/test/") and then substring.

  • In your examples, it seems like you're interested in the very last part, which could be retrieved by lastIndexOf('/') for instance.

  • Or, using look-arounds you could do

    String s1 = "https://www.ppltalent.com/test/en/soln-computers-ltd";
    
    String[] parts = s1.split("(?<=/test/../)");
    System.out.println(parts[0]);  // https://www.ppltalent.com/test/er/
    System.out.println(parts[1]);  // soln-computers-ltd
    

Upvotes: 5

Diego Martinoia
Diego Martinoia

Reputation: 4662

Split on the last /

String fullUrl = "https:////www.ppltalent.com//test//en//soln-computers-ltd";
String baseUrl = fullUrl.substring(0, fullUrl.lastIndexOf("//"));
String manufacturer = fullUrl.subString(fullUrl.lastIndexOf("//"));

Upvotes: -1

Related Questions