【问题标题】:Java: Counting frequency of a sequence in a stringJava:计算字符串中序列的频率
【发布时间】:2017-06-12 17:06:50
【问题描述】:

我正在编写一个简单的程序来计算一个序列在字符串中出现的次数。

案例一:

给定字符串: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); 

    }
}

我的程序在第 1 种情况下工作。它在第 2 种情况下失败,因为s.split(sequence) 删除了两个 'EAT',留下一个大小为 0 的数组。

有没有办法解决这个问题?

【问题讨论】:

  • 不要使用String#split,而是自己循环解析String。
  • 一个不错的 indexOf 循环
  • 重叠匹配怎么办?比如你在“EEE”中搜索“EE”,是2还是3?
  • @shmosel 是 1
  • 糟糕,我的意思是 1 或 2。

标签: java arrays string split count


【解决方案1】:

为此使用正则表达式:

Pattern pattern = Pattern.compile(sequence);
Matcher  matcher = pattern.matcher(s);

int count = 0;
while (matcher.find())
    count++;

System.out.println(count);

【讨论】:

  • 这行得通。但是有没有类似于我的解决方案?
【解决方案2】:

一种选择是使用replace() 删除匹配项并计算大小差异:

int count = (s.length() - s.replace(sequence, "").length()) / sequence.length();

如果你想使用split() 方法,如果你像这样使用它应该可以工作:

int count = s.split(sequence, -1).length - 1;

-1 参数告诉方法不要丢弃尾随的空字符串。然后我们从长度中减去 1 来避免栅栏问题。

【讨论】:

  • 我不明白。在 EATEAT 上执行此操作会返回 6。
【解决方案3】:

这里还有一个您想尝试的选项

     int count=0;
if(s.endsWith(sequence)){
     count=s.split(sequence).length;}
else{
  count=s.split(sequence).length-1;
}

【讨论】:

    猜你喜欢
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 2016-05-18
    • 2017-04-19
    • 1970-01-01
    • 2023-03-25
    • 2011-10-06
    相关资源
    最近更新 更多