Newbie Java - IndexOf() problem

J

john

Can anyone tell me how to use the indexOf() function to count the
number of occurences of a specified character in a user defined
string.

Any help would be most appreciated.

John
 
J

Jeffrey Palm

john said:
Can anyone tell me how to use the indexOf() function to count the
number of occurences of a specified character in a user defined
string.

Any help would be most appreciated.

John

public class Count {
public static void main(String[] args) {
if (args.length == 0) args = new String[]{"abbcccdddeeee"};
final char C = 'c'; // we're counting c's
for (int i = 0; i < args.length; i++) {
String str = args;
System.out.println(count(C,str) + " " + C + " in '" + str + "'");
}
}
static int count(char c, String str) {
if (str == null) return 0;
int cnt = 0;
for (int i = 0;; cnt++) {
if ((i = str.indexOf(c,i)+1) == 0) break;
}
return cnt;
}
}
 
C

Christophe Vanfleteren

john said:
Can anyone tell me how to use the indexOf() function to count the
number of occurences of a specified character in a user defined
string.

Any help would be most appreciated.

John

What was wrong with all the answer that already have been given to you?
 
J

john

Christophe Vanfleteren said:
What was wrong with all the answer that already have been given to you?

Hi Christophe, there's nothing at all wrong with your answer, things
have just got mixed up, nothing more.

Many thanks for your kind assistance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,787
Messages
2,569,631
Members
45,338
Latest member
41Pearline46

Latest Threads

Top