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.
kkbenjAsked:
Who is Participating?
 
CEHJCommented:
e.g. for String 's', this will print the index of the 3rd '/' (if there is one)
Pattern p = Pattern.compile(".*?/.*?/.*?(/)");
	Matcher m = p.matcher(s);
	if(m.find()) {
	    System.out.println(m.start(1));
	}

Open in new window

0
 
CEHJCommented:
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?
0
 
for_yanCommented:
if you know that this is  this is the last occurrence you can use
lastIndexOf()

0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
CEHJCommented:
Matcher.find will find the beginning of the match if you give it the right pattern
0
 
cmalakarCommented:
sVariable.matches(".*/.*/.*/.*");
0
 
CEHJCommented:
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

0
 
cmalakarCommented:
Sorry overlooked at your question..

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

will print "f"
0
 
objectsCommented:
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;
}
0
 
CEHJCommented:
:)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.