Java代码实现统计一段代码中的关键词个数
时间: 2023-07-02 11:14:34 浏览: 97
可以使用Java中的正则表达式和Map来实现统计关键词个数的功能。具体实现步骤如下:
1. 定义一个字符串数组,存储需要统计的关键词。
2. 使用正则表达式匹配代码中的关键词,并将匹配到的关键词存储到Map中。
3. 遍历Map,统计每个关键词出现的次数。
以下是代码示例:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class KeywordCounter {
public static void main(String[] args) {
String code = "public class Test {\n" +
" public static void main(String[] args) {\n" +
" int a = 1;\n" +
" int b = 2;\n" +
" System.out.println(\"a + b = \" + (a + b));\n" +
" }\n" +
"}";
String[] keywords = {"public", "class", "static", "void", "main", "String", "int", "System", "out", "println"};
Map<String, Integer> keywordMap = new HashMap<>();
for (String keyword : keywords) {
String regex = "\\b" + keyword + "\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(code);
int count = 0;
while (matcher.find()) {
count++;
}
keywordMap.put(keyword, count);
}
for (Map.Entry<String, Integer> entry : keywordMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
输出结果为:
```
public: 1
class: 1
static: 1
void: 1
main: 1
String: 1
int: 2
System: 1
out: 1
println: 1
```
阅读全文