Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get substring between "first two" occurrences of a character

I have a String:

 String thestra = "/aaa/bbb/ccc/ddd/eee";

Every time, in my situation, for this Sting, a minimum of two slashes will be present without fail.

And I am getting the /aaa/ like below, which is the subString between "FIRST TWO occurrences" of the char / in the String.

 System.out.println("/" + thestra.split("\\/")[1] + "/");

It solves my purpose but I am wondering if there is any other elegant and cleaner alternative to this?

Please notice that I need both slashes (leading and trailing) around aaa. i.e. /aaa/

like image 242
Ajay Kumar Avatar asked Dec 03 '22 09:12

Ajay Kumar


2 Answers

You can use indexOf, which accepts a second argument for an index to start searching from:

int start = thestra.indexOf("/");
int end = thestra.indexOf("/", start + 1) + 1;
System.out.println(thestra.substring(start, end));

Whether or not it's more elegant is a matter of opinion, but at least it doesn't find every / in the string or create an unnecessary array.

like image 198
kaya3 Avatar answered Feb 09 '23 01:02

kaya3


Scanner::findInLine returning the first match of the pattern may be used:

String thestra = "/aaa/bbb/ccc/ddd/eee";
System.out.println(new Scanner(thestra).findInLine("/[^/]*/"));

Output:

/aaa/
like image 33
Nowhere Man Avatar answered Feb 09 '23 01:02

Nowhere Man