[英]How To Find The Repeated occurrence of substring in String Using Java Stream API
[英]How to count the frequent occurrence of distinct substring (Math symbols) in a string using Java or R
我有以下字符串( 子字符串之間有時沒有空格 ):
str = "<= < / + * + cos sin (service <= service)+ * hello)rate"
子字符串已經預先定義,例如:
mathsubstring = {<=, <, / , +, cos, sin }
並且普通的子字符串也是預定義的:
substring[]= {"service","hi","rate","world"};
我想計算每個特定子字符串的頻繁出現次數,例如:
The output will be :
<= = 2
< = 1
/ = 1
+ = 3
* = 2
cos = 1
sin = 1
到目前為止,我設法從字符串中找到了子字符串,請參見以下Java代碼:
String substring[]= {"service","hi","rate","world"};
int count=0;
for (int j=0; j< substring.length; j++)
{
count=0;
Pattern p = Pattern.compile("\\b"+substring[j]+"\\b");
Matcher m = p.matcher(str);
while(m.find()) {
count++;
}
Countsubstring = Countsubstring + count;
}
提前致謝。
用R
的方式,在每個space
處分割字符串,然后計算不同元素的出現次數:
編輯
使用第三個字符串和新的約束,考慮元素可以用空格或左括號或右括號分隔:
str <- "<= < / + * + cos sin (service <= service)+ * hello)rate"
mathsubstring <- c("<=", "<", "/", "+", "cos", "sin")
t_elt <- table(strsplit(str, " |\\(|\\)"))
t_elt[mathsubstring]
<= < / + cos sin 2 1 1 3 1 1
如果您想知道數學子字符串出現的總數:
sum(t_elt[mathsubstring])
#[1] 9
以前的str
先前代碼
table(strsplit(str, " "))
* / + < <= cos service sin
2 1 3 1 2 1 2 1
之后,您可以根據需要刪除service
(或其他非數學符號),例如:
tab <- table(strsplit(str, " "))
mathsubstring <- c('<=', '<', '/', '+', 'cos', 'sin')
tab[names(tab) %in% mathsubstring]
用第二個字符串:
str = "<= < / + * + cos sin service <= service + * hello rate"
table(strsplit(str, " "))
* / + < <= cos hello rate service sin
2 1 3 1 2 1 1 1 2 1
這就是我所做的:
String str = "<= < / + * + cos sin service <= service + *";
String[] split = str.split(" ");
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (String subString : split) {
if (!map.containsKey(subString)) {
map.put(subString, 0);
}
Integer current = map.get(subString);
map.put(subString, ++current);
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(String.format("%s = %s",entry.getKey(),entry.getValue()));
}
您可以使用分組和計數收集器。
Arrays.stream(str.split(" "))
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
這將導致Map<String, Long>
具有以下內容:
{<==2, service=2, cos=1, sin=1, *=2, +=3, <=1, /=1}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.