• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 481
  • Last Modified:

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.
0
kkbenj
Asked:
kkbenj
1 Solution
 
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
 
CEHJCommented:
Matcher.find will find the beginning of the match if you give it the right pattern
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
cmalakarCommented:
sVariable.matches(".*/.*/.*/.*");
0
 
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:
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

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now