[英]count character occurrences in a string in Java
我試圖讓它打印有多少個字母“a”。 它一直給我0 ...有什么幫助嗎?
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File myfile = chooser.getSelectedFile();
try {
Scanner in = new Scanner(myfile);
String word = in.nextLine();
int counter = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a') {
counter++;
}
}
System.out.println("# of chars: " + counter);
} catch (IOException e) {
System.err.println("A reading error occured");
}
}
一種簡單的(一行)計數出現的字符的方法是:
int count = word.replaceAll("[^a]", "").length();
這將用空格替換不是“ a”的每個字符-有效地將其刪除-留下一個僅包含原始字符串的“ a”字符的字符串,然后得到該字符串的長度。
除了讀取文件的任何問題外,還請嘗試使用StringUtils countMatches。 它已經在通用語言中,請記住也要使用它。
例如
int count = StringUtils.countMatches(word, "a");
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File myfile = chooser.getSelectedFile();
try {
Scanner in = new Scanner(myfile);
int counter = 0;
while(in.hasNextLine()){
String word = in.nextLine();
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a') {
counter++;
}
}
}
System.out.println("# of chars: " + counter);
} catch (IOException e) {
System.err.println("A reading error occured");
}
}
/* 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.