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,(sVa r2.indexOf ("/")+1))
will give me the first occurrence.
PWo = sVariable.substring(0,(sVa
will give me the first occurrence.
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()
lastIndexOf()
Matcher.find will find the beginning of the match if you give it the right pattern
sVariable.matches(".*/.*/. */.*");
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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)
Sorry overlooked at your question..
String s = "a/bc/cd/f";
System.out.println(s.repla ceAll(".*/ .*/.*/(.*) ", "$1"));
will print "f"
String s = "a/bc/cd/f";
System.out.println(s.repla
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;
}
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;
}
:)