![](/img/trans.png)
[英]I want to find Java program to count the occurrence of each character in a string without using Hashmap or array concept
[英]How to count occurrence of each character in java string using Pattern Class(Regex)
我正在嘗試查找給定字符串中每個字符的出現次數。
t=2 e=1 s=1 i=1 n=1 g=1
T=0 e=0 s=0 t=0 i=0 n=0 g=0
碼:
String str = "Testing";
int count = 0;
Pattern p = Pattern.compile("[a-zA-Z]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
while (m.find()) {
if (m.group().equals(str)) {
count++;
}
System.out.println(m.group() + "=" + count);
}
有很多方法可以做到這一點,但是我只在尋找Regex,所以如何使用Regex來實現這一目標。 任何幫助,將不勝感激。 提前致謝。
無需正則表達式即可解決您的問題,如果您使用的是Java8 +,則可以使用:
String input = "Testing";
Map<String, Long> result = Arrays.stream(input.split(""))
.map(String::toLowerCase)
.collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));
輸出
{t=2, e=1, s=1, i=1, n=1, g=1}
編輯
嗯,在這種情況下,模式是沒有用的,我不建議在此問題中使用它,作為使用模式的替代解決方案,並且可以使用Java9 +的結果,您可以使用:
String str = "Testing";
Pattern.compile(".").matcher(str)
.results()
.map(m -> m.group().toLowerCase())
.collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()))
.forEach((k, v) -> System.out.println(k + " = " + v));
產出
t = 2
e = 1
s = 1
i = 1
n = 1
g = 1
有很多方法可以達到目的,但是Regex並不是實現這一目標的工具。 如果要過濾字符並確保僅計算[a-zA-Z]
,請使用以下方法過濾不需要的字符: string = string.replaceAll("[^a-zA-Z]", "");
。 現在回到您的問題。
您需要將String
拆分為字符,然后使用Map<Character, Integer>
來存儲這些字符及其出現的次數。 我建議您使用LinkedHashMap<Character, Integer>
來確保插入順序。
char[] charArray = string.toCharArray();
Map<Character, Integer> map = new LinkedHashMap<>();
現在遍歷角色並將其保存到地圖。 如果已經存儲了一個字符,則將該值加1。 這可以通過過程式和傳統的for-loop
來實現,或者因為Java 8您可以使用java-stream 。
在Java 8之前:
for (char ch: charArray) {
if(map.containsKey(ch)){
map.put(ch, map.get(ch)+1);
} else {
map.put(ch, 1);
}
}
Java 8( string.split("")
返回字符串數組之后,您需要將它們映射到字符):
Map<Character, Long> map = Arrays
.asList(string.split("")).stream().map(s -> s.charAt(0))
.collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));
在這兩種情況下,輸出都是相同的:
System.out.println(map); // prints {t=2, e=1, s=1, i=1, n=1, g=1}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.