-2

I have a string of names where all the different names are seperated by the same character (#) e.g. tom#will#robert#

I want to be able to count the number of names by counting the number of times that # appears, How would i go about doing this?

Matt
  • 1,471
  • 8
  • 20
  • 28
  • possible duplicate of [How do I count the number of occurrences of a char in a String?](http://stackoverflow.com/questions/275944/how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string) – Brendan Long Nov 25 '11 at 21:10

2 Answers2

4

You need:

yourstring.splt("#").length;
勿绮语
  • 9,170
  • 1
  • 29
  • 37
  • 1
    ...only other thing is to perhaps subtract 1 iff the string does not end with a #. Also, for very, very long Strings, manually counting may be more processor/memory friendly. – Jaco Van Niekerk Nov 25 '11 at 21:14
0

Why would you want to count the number of tokens by counting the number of the delimiters?

Just use StringTokenizer to get all tokens (set the delimiter as #) and then get its size.

StringTokenizer(String str, String delim)
      Constructs a string tokenizer for the specified string.

then:

 int    countTokens()
      Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.
Mechkov
  • 4,294
  • 1
  • 17
  • 25