我正在编写一个简单的程序,用于计算序列在字符串中出现的次数。
案例1:
给定字符串:EATNEATMMMMEAT
给定序列:EAT
程序应返回值 3。
案例2:
给定字符串:EATEAT
给定序列:EAT
程序应该返回 2。
import java.util.*;
public class FrequencyOfSequence { //Finds the frequency of a sequence in a string s
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
String sequence = in.nextLine();
String[] cArr = s.split(sequence);
System.out.println(cArr.length);
}
}
我的程序在第一种情况下可以工作。在第二种情况下它会失败,因为 s.split(sequence)
删除了两个“EAT”,留下了一个大小为 0 的数组。
有办法解决这个问题吗?
最佳答案
为此使用正则表达式:
Pattern pattern = Pattern.compile(sequence);
Matcher matcher = pattern.matcher(s);
int count = 0;
while (matcher.find())
count++;
System.out.println(count);
关于Java:计算字符串中序列的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41886824/