Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

300
Views
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/

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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/
over 4 years ago · Santiago Trujillo Report

0

Use Pattern and Matcher from java.util.regex.

Pattern pattern = Pattern.compile("/.*?/");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) { 
    String match = matcher.group(0);  // output
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!