[英]Counting character occurrences in a string - Java
我在編寫一個采用字符串並計算第一個字符(或實際上任何字符)出現的次數的方法時遇到問題。 我編寫的代碼如下,但由於某種原因,當我運行它時,它總是返回正確計數的一半。 任何幫助將不勝感激,謝謝。
public static void countOccurrences(String string1) {
int counter = 0;
char toCheck = string1.charAt(0);
char compareChar;
for (int i = 0; i < string1.length(); i++) {
compareChar = string1.charAt(i);
if (toCheck == compareChar) {
counter++;
}
i++;
}
System.out.println(toCheck + " appears " + counter + " times in string1.");
}
你遞增i
兩次,每次迭代中,所以你跳過半個漢字:
for (int i = 0; i < string1.length(); i++) { // i is incremented here
compareChar = string1.charAt(i);
if (toCheck == compareChar){
counter++ ;
}
i++ ; // i is incremented again here - remove this line
}
你當前的問題是i++;
每次迭代發生兩次。
另一種方法是使用
s.length() - s.replace("x", "").length()
它給出了"x"
出現在s
。 可以說它不是最有效的方式,但很明顯。
i ++ for for循環將i值遞增1,無需在eloop內遞增
public static void countOccurrences(String string1) {
int counter = 0;
char toCheck = string1.charAt(0);
char compareChar;
for (int i = 0; i < string1.length(); i++) {
compareChar = string1.charAt(i);
if (toCheck == compareChar){
counter++ ;
}
}
System.out.println(toCheck + " appears " + counter + " times in string1.");
}
/* Most common string occurrence related solutions using java 8 */
//find all character occurrences in a string
String myString = "test";
List<Character> list = myString.chars().mapToObj(c -> (char)c).collect(Collectors.toList());
list.stream().distinct().forEach(c -> System.out.println(c + " = " + Collections.frequency(list, c)));
//find one specific character occurrence in a string
String myString = "test";
char search = 't';
long count = myString.chars().filter(c -> c == search).count();
System.out.println(count);
//find all unique characters in a string
String myString = "test";
List<Character> list = myString.chars().mapToObj(c -> (char)c).collect(Collectors.toList());
list.stream().filter(c -> Collections.frequency(list,c) == 1).forEach(System.out::println);
//find first unique character in a string
String myString = "test";
List<Character> list = myString.chars().mapToObj(c -> (char)c).collect(Collectors.toList());
char firstUniqueChar = list.stream().filter(c -> Collections.frequency(list,c) == 1).findFirst().get();
System.out.println(firstUniqueChar);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.