Link to home
Start Free TrialLog in
Avatar of kkbenj
kkbenj

asked on

Java multiple occurrences within a string

Is there a faster way to find the third occurrence of a character within a string, rather than looping?

PWo = sVariable.substring(0,(sVar2.indexOf("/")+1))
will give me the first occurrence.
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Not really. Whatever is doing the finding will have to loop. Of course, you can try to avoid doing it yourself, even if something else has to. What exactly is it that you need to get?
if you know that this is  this is the last occurrence you can use
lastIndexOf()

Matcher.find will find the beginning of the match if you give it the right pattern
sVariable.matches(".*/.*/.*/.*");
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
And of course if you want the remainder of the String
s = s.replaceAll(".*?/.*?/.*?(/.*)", "$1"); // (with the slash)

or

s = s.replaceAll(".*?/.*?/.*?/(.*)", "$1"); // (without the slash)

Open in new window

Sorry overlooked at your question..

String s = "a/bc/cd/f";
System.out.println(s.replaceAll(".*/.*/.*/(.*)", "$1"));

will print "f"
A simple loop will be the fastest, something like this:

int matches = 0;
int index = -1;
for (int i=0; i<s.length() && matches<3; i++) {
   if (s.charAt(i)=='/') matches++;
   if (matches==3) index = i;
}
:)