2011-11-25 96 views
-2

我有一個名稱的字符串,其中所有不同的名稱由相同的字符(#)分隔。 tom#will#robert#在java中計算字符串中字符的確切數量

我想通過計算#出現的次數來計算名稱的數量,我該如何去做這件事?

+0

可能重複:// stackoverflow.com/questions/275944/how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string) –

回答

4

您需要:

yourstring.splt("#").length; 
的[我如何計算一個串一個字符的出現的次數?](HTTP
+1

...只有其他的事情是或許減去1 iff字符串不以#結尾。而且,對於非常非常長的字符串,手動計數可能更適合處理器/內存。 –

0

爲什麼要通過計算分隔符的數量來計算令牌的數量?

只需使用StringTokenizer獲取所有令牌(將分隔符設置爲#),然後獲取其大小。

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

則:

int countTokens() 
     Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.