I have a string(s) ( NOT Path
or File
-path ) like below:
String str1 = "/first/second/third/fourth/fifth";
String str2 = "/foo/bar/blah";
GIVEN: The string will always start with leading slash and there are guaranteed minimum two slashes (can be more too, as above) and some substring after that.
Now I am trying to capture the entire substring "after-first-two-slashes"
. So that my output becomes:
Output:
str1_becomes = /second/third/fourth/fifth
str2_becomes = /bar/blah
Please note that I want to retain the leading slash too. What efficient approach should I follow to achieve it? Need some directions/clues as feeling lost here. Preferably java 1.8 based.
CodePudding user response:
You can easily do this using simple string operations.
If the string always begins with a slash and has two slashes, you could just use indexOf for finding the second slash's position:
str1.indexOf('/',1);
This looks for the first slash starting with the second character.
After that, you can use substring for getting tje resulting string (starting with the index you just found out):
str1.substring(str1.indexOf('/',1));
If the first slash is not necessarily the first character, you can search for the first slash using indexOf and use that result 1 as the start index for searching the second slash:
str1.substring(str1.indexOf('/',str1.indexOf('/')));