查找字符串中子字符串的出现次数

发布于 2024-07-18 02:11:58 字数 431 浏览 5 评论 0原文

为什么以下算法不会对我停止?

在下面的代码中,str 是我要搜索的字符串,findStr 是我要查找的字符串出现次数。

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
    
while (lastIndex != -1) {
    lastIndex = str.indexOf(findStr,lastIndex);
    
    if( lastIndex != -1)
        count++;
           
    lastIndex += findStr.length();
}

System.out.println(count);

Why is the following algorithm not halting for me?

In the code below, str is the string I am searching in, and findStr is the string occurrences of which I'm trying to find.

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
    
while (lastIndex != -1) {
    lastIndex = str.indexOf(findStr,lastIndex);
    
    if( lastIndex != -1)
        count++;
           
    lastIndex += findStr.length();
}

System.out.println(count);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

清欢 2024-07-25 02:11:59

您的 lastIndex += findStr.length(); 被放置在括号之外,导致无限循环(当未找到任何情况时,lastIndex 始终为 findStr.length() )。

这是固定版本:

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while (lastIndex != -1) {

    lastIndex = str.indexOf(findStr, lastIndex);

    if (lastIndex != -1) {
        count++;
        lastIndex += findStr.length();
    }
}
System.out.println(count);

Your lastIndex += findStr.length(); was placed outside the brackets, causing an infinite loop (when no occurence was found, lastIndex was always to findStr.length()).

Here is the fixed version :

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while (lastIndex != -1) {

    lastIndex = str.indexOf(findStr, lastIndex);

    if (lastIndex != -1) {
        count++;
        lastIndex += findStr.length();
    }
}
System.out.println(count);
面如桃花 2024-07-25 02:11:59

较短的版本。 ;)

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(str.split(findStr, -1).length-1);

A shorter version. ;)

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(str.split(findStr, -1).length-1);
随风而去 2024-07-25 02:11:59

最后一行造成了问题。 lastIndex 永远不会是 -1,所以会出现无限循环。 可以通过将最后一行代码移至 if 块来解决此问题。

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while(lastIndex != -1){

    lastIndex = str.indexOf(findStr,lastIndex);

    if(lastIndex != -1){
        count ++;
        lastIndex += findStr.length();
    }
}
System.out.println(count);

The last line was creating a problem. lastIndex would never be at -1, so there would be an infinite loop. This can be fixed by moving the last line of code into the if block.

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while(lastIndex != -1){

    lastIndex = str.indexOf(findStr,lastIndex);

    if(lastIndex != -1){
        count ++;
        lastIndex += findStr.length();
    }
}
System.out.println(count);
你是年少的欢喜 2024-07-25 02:11:59

您真的需要自己处理匹配吗? 特别是如果您需要的只是出现的次数,则正则表达式更加整洁:

String str = "helloslkhellodjladfjhello";
Pattern p = Pattern.compile("hello");
Matcher m = p.matcher(str);
int count = 0;
while (m.find()){
    count +=1;
}
System.out.println(count);     

Do you really have to handle the matching yourself ? Especially if all you need is the number of occurences, regular expressions are tidier :

String str = "helloslkhellodjladfjhello";
Pattern p = Pattern.compile("hello");
Matcher m = p.matcher(str);
int count = 0;
while (m.find()){
    count +=1;
}
System.out.println(count);     
浅笑轻吟梦一曲 2024-07-25 02:11:59

我很惊讶没有人提到这一班轮。 它简单、简洁,并且性能略优于 str.split(target, -1).length-1

public static int count(String str, String target) {
    return (str.length() - str.replace(target, "").length()) / target.length();
}

I'm very surprised no one has mentioned this one liner. It's simple, concise and performs slightly better than str.split(target, -1).length-1

public static int count(String str, String target) {
    return (str.length() - str.replace(target, "").length()) / target.length();
}
维持三分热 2024-07-25 02:11:59

在这里,它被封装在一个漂亮且可重用的方法中:

public static int count(String text, String find) {
        int index = 0, count = 0, length = find.length();
        while( (index = text.indexOf(find, index)) != -1 ) {                
                index += length; count++;
        }
        return count;
}

Here it is, wrapped up in a nice and reusable method:

public static int count(String text, String find) {
        int index = 0, count = 0, length = find.length();
        while( (index = text.indexOf(find, index)) != -1 ) {                
                index += length; count++;
        }
        return count;
}
喜你已久 2024-07-25 02:11:59
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
     count++;
     lastIndex += findStr.length() - 1;
}
System.out.println(count);

循环结束时计数为 3; 希望能帮助到你

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
     count++;
     lastIndex += findStr.length() - 1;
}
System.out.println(count);

at the end of the loop count is 3; hope it helps

梦毁影碎の 2024-07-25 02:11:59
public int countOfOccurrences(String str, String subStr) {
  return (str.length() - str.replaceAll(Pattern.quote(subStr), "").length()) / subStr.length();
}
public int countOfOccurrences(String str, String subStr) {
  return (str.length() - str.replaceAll(Pattern.quote(subStr), "").length()) / subStr.length();
}
眼趣 2024-07-25 02:11:59

许多给出的答案在以下一项或多项方面失败:

  • 任意长度的模式
  • 重叠匹配(例如计算“23232”中的“232”或“aaa”中的“aa”)
  • 正则表达式元字符

这是我写的:

static int countMatches(Pattern pattern, String string)
{
    Matcher matcher = pattern.matcher(string);

    int count = 0;
    int pos = 0;
    while (matcher.find(pos))
    {
        count++;
        pos = matcher.start() + 1;
    }

    return count;
}

示例调用:

Pattern pattern = Pattern.compile("232");
int count = countMatches(pattern, "23232"); // Returns 2

如果您想要非正则表达式搜索,只需使用 LITERAL 标志适当地编译您的模式:

Pattern pattern = Pattern.compile("1+1", Pattern.LITERAL);
int count = countMatches(pattern, "1+1+1"); // Returns 2

A lot of the given answers fail on one or more of:

  • Patterns of arbitrary length
  • Overlapping matches (such as counting "232" in "23232" or "aa" in "aaa")
  • Regular expression meta-characters

Here's what I wrote:

static int countMatches(Pattern pattern, String string)
{
    Matcher matcher = pattern.matcher(string);

    int count = 0;
    int pos = 0;
    while (matcher.find(pos))
    {
        count++;
        pos = matcher.start() + 1;
    }

    return count;
}

Example call:

Pattern pattern = Pattern.compile("232");
int count = countMatches(pattern, "23232"); // Returns 2

If you want a non-regular-expression search, just compile your pattern appropriately with the LITERAL flag:

Pattern pattern = Pattern.compile("1+1", Pattern.LITERAL);
int count = countMatches(pattern, "1+1+1"); // Returns 2
浊酒尽余欢 2024-07-25 02:11:59

您可以使用内置库函数计算出现次数:

import org.springframework.util.StringUtils;
StringUtils.countOccurrencesOf(result, "R-")

You can number of occurrences using inbuilt library function:

import org.springframework.util.StringUtils;
StringUtils.countOccurrencesOf(result, "R-")
甜嗑 2024-07-25 02:11:59

每当您查找下一个匹配项时,都会增加 lastIndex

否则它总是找到第一个子字符串(位于位置 0)。

Increment lastIndex whenever you look for next occurrence.

Otherwise it's always finding the first substring (at position 0).

尐偏执 2024-07-25 02:11:59

Matcher.results()

您可以使用 Java 9 方法 Matcher.results() 和单个行代码。

它生成与捕获的子字符串相对应的 MatchResult 对象流,唯一需要的是应用 Stream.count() 获取数量流中的元素。

public static long countOccurrences(String source, String find) {
    
    return Pattern.compile(find) // Pattern
        .matcher(source) // Mather
        .results()       // Stream<MatchResults>
        .count();
}

main()

public static void main(String[] args) {
    System.out.println(countOccurrences("helloslkhellodjladfjhello", "hello"));
}

输出:

3

Matcher.results()

You can find the number of occurrences of a substring in a string using Java 9 method Matcher.results() with a single line of code.

It produces a Stream of MatchResult objects which correspond to captured substrings, and the only thing needed is to apply Stream.count() to obtain the number of elements in the stream.

public static long countOccurrences(String source, String find) {
    
    return Pattern.compile(find) // Pattern
        .matcher(source) // Mather
        .results()       // Stream<MatchResults>
        .count();
}

main()

public static void main(String[] args) {
    System.out.println(countOccurrences("helloslkhellodjladfjhello", "hello"));
}

Output:

3
秋叶绚丽 2024-07-25 02:11:59

给出的正确答案对于计算行返回之类的东西没有好处,而且太冗长了。 后来的答案更好,但所有这些都可以通过

str.split(findStr).length

使用问题中的示例来实现,它不会删除尾随匹配项。

The answer given as correct is no good for counting things like line returns and is far too verbose. Later answers are better but all can be achieved simply with

str.split(findStr).length

It does not drop trailing matches using the example in the question.

孤独患者 2024-07-25 02:11:59
public int indexOf(int ch,
                   int fromIndex)

返回此字符串中指定字符第一次出现的索引,从指定索引处开始搜索。

因此,您的 lastindex 值始终为 0,并且它总是在字符串中找到 hello

public int indexOf(int ch,
                   int fromIndex)

Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

So your lastindex value is always 0 and it always finds hello in the string.

纵性 2024-07-25 02:11:59

尝试将 lastIndex+=findStr.length() 添加到循环末尾,否则您将陷入无限循环,因为一旦找到子字符串,您就会尝试一次又一次地从相同的最后位置。

try adding lastIndex+=findStr.length() to the end of your loop, otherwise you will end up in an endless loop because once you found the substring, you are trying to find it again and again from the same last position.

前事休说 2024-07-25 02:11:59

试试这个。 它将所有匹配项替换为 -

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int numberOfMatches = 0;
while (str.contains(findStr)){
    str = str.replaceFirst(findStr, "-");
    numberOfMatches++;
}

如果您不想破坏您的 str 您可以创建一个具有相同内容的新字符串:

String str = "helloslkhellodjladfjhello";
String strDestroy = str;
String findStr = "hello";
int numberOfMatches = 0;
while (strDestroy.contains(findStr)){
    strDestroy = strDestroy.replaceFirst(findStr, "-");
    numberOfMatches++;
}

执行此块后,这些将是您的值:

str = "helloslkhellodjladfjhello"
strDestroy = "-slk-djladfj-"
findStr = "hello"
numberOfMatches = 3

Try this one. It replaces all the matches with a -.

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int numberOfMatches = 0;
while (str.contains(findStr)){
    str = str.replaceFirst(findStr, "-");
    numberOfMatches++;
}

And if you don't want to destroy your str you can create a new string with the same content:

String str = "helloslkhellodjladfjhello";
String strDestroy = str;
String findStr = "hello";
int numberOfMatches = 0;
while (strDestroy.contains(findStr)){
    strDestroy = strDestroy.replaceFirst(findStr, "-");
    numberOfMatches++;
}

After executing this block these will be your values:

str = "helloslkhellodjladfjhello"
strDestroy = "-slk-djladfj-"
findStr = "hello"
numberOfMatches = 3
猛虎独行 2024-07-25 02:11:59

正如@Mr_and_Mrs_D 建议的:

String haystack = "hellolovelyworld";
String needle = "lo";
return haystack.split(Pattern.quote(needle), -1).length - 1;

As @Mr_and_Mrs_D suggested:

String haystack = "hellolovelyworld";
String needle = "lo";
return haystack.split(Pattern.quote(needle), -1).length - 1;
筱武穆 2024-07-25 02:11:59

根据现有的答案,我想添加一个不带 if 的“较短”版本:

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

int count = 0, lastIndex = 0;
while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
    lastIndex += findStr.length() - 1;
    count++;
}

System.out.println(count); // output: 3

Based on the existing answer(s) I'd like to add a "shorter" version without the if:

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

int count = 0, lastIndex = 0;
while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
    lastIndex += findStr.length() - 1;
    count++;
}

System.out.println(count); // output: 3
掩耳倾听 2024-07-25 02:11:59

这是用于计算令牌在用户输入的字符串中出现的次数的高级版本:

public class StringIndexOf {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a sentence please: \n");
        String string = scanner.nextLine();

        int atIndex = 0;
        int count = 0;

        while (atIndex != -1)
        {
            atIndex = string.indexOf("hello", atIndex);

            if(atIndex != -1)
            {
                count++;
                atIndex += 5;
            }
        }

        System.out.println(count);
    }

}

Here is the advanced version for counting how many times the token occurred in a user entered string:

public class StringIndexOf {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a sentence please: \n");
        String string = scanner.nextLine();

        int atIndex = 0;
        int count = 0;

        while (atIndex != -1)
        {
            atIndex = string.indexOf("hello", atIndex);

            if(atIndex != -1)
            {
                count++;
                atIndex += 5;
            }
        }

        System.out.println(count);
    }

}
╰つ倒转 2024-07-25 02:11:59

下面的方法显示了子字符串在整个字符串上重复的次数。 希望对您有用:-

    String searchPattern="aaa"; // search string
    String str="aaaaaababaaaaaa"; // whole string
    int searchLength = searchPattern.length(); 
    int totalLength = str.length(); 
    int k = 0;
    for (int i = 0; i < totalLength - searchLength + 1; i++) {
        String subStr = str.substring(i, searchLength + i);
        if (subStr.equals(searchPattern)) {
           k++;
        }

    }

This below method show how many time substring repeat on ur whole string. Hope use full to you:-

    String searchPattern="aaa"; // search string
    String str="aaaaaababaaaaaa"; // whole string
    int searchLength = searchPattern.length(); 
    int totalLength = str.length(); 
    int k = 0;
    for (int i = 0; i < totalLength - searchLength + 1; i++) {
        String subStr = str.substring(i, searchLength + i);
        if (subStr.equals(searchPattern)) {
           k++;
        }

    }
不喜欢何必死缠烂打 2024-07-25 02:11:59

该解决方案打印给定子字符串在整个字符串中出现的总数,还包括确实存在重叠匹配的情况。

class SubstringMatch{
    public static void main(String []args){
        //String str = "aaaaabaabdcaa";
        //String sub = "aa";
        //String str = "caaab";
        //String sub = "aa";
        String str="abababababaabb";
        String sub = "bab";

        int n = str.length();
        int m = sub.length();

        // index=-1 in case of no match, otherwise >=0(first match position)
        int index=str.indexOf(sub), i=index+1, count=(index>=0)?1:0;
        System.out.println(i+" "+index+" "+count);

        // i will traverse up to only (m-n) position
        while(index!=-1 && i<=(n-m)){   
            index=str.substring(i, n).indexOf(sub);
            count=(index>=0)?count+1:count;
            i=i+index+1;  
            System.out.println(i+" "+index);
        }
        System.out.println("count: "+count);
    }
}

This solution prints the total number of occurrence of a given substring throughout the string, also includes the cases where overlapping matches do exist.

class SubstringMatch{
    public static void main(String []args){
        //String str = "aaaaabaabdcaa";
        //String sub = "aa";
        //String str = "caaab";
        //String sub = "aa";
        String str="abababababaabb";
        String sub = "bab";

        int n = str.length();
        int m = sub.length();

        // index=-1 in case of no match, otherwise >=0(first match position)
        int index=str.indexOf(sub), i=index+1, count=(index>=0)?1:0;
        System.out.println(i+" "+index+" "+count);

        // i will traverse up to only (m-n) position
        while(index!=-1 && i<=(n-m)){   
            index=str.substring(i, n).indexOf(sub);
            count=(index>=0)?count+1:count;
            i=i+index+1;  
            System.out.println(i+" "+index);
        }
        System.out.println("count: "+count);
    }
}
じ违心 2024-07-25 02:11:59

这是不使用 regexp/patterns/matchers 甚至不使用 StringUtils 的另一个解决方案。

String str = "helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello";
        String findStr = "hello";
        int count =0;
        int findStrLength = findStr.length();
        for(int i=0;i<str.length();i++){
            if(findStr.startsWith(Character.toString(str.charAt(i)))){
                if(str.substring(i).length() >= findStrLength){
                    if(str.substring(i, i+findStrLength).equals(findStr)){
                        count++;
                    }
                }
            }
        }
        System.out.println(count);

here is the other solution without using regexp/patterns/matchers or even not using StringUtils.

String str = "helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello";
        String findStr = "hello";
        int count =0;
        int findStrLength = findStr.length();
        for(int i=0;i<str.length();i++){
            if(findStr.startsWith(Character.toString(str.charAt(i)))){
                if(str.substring(i).length() >= findStrLength){
                    if(str.substring(i, i+findStrLength).equals(findStr)){
                        count++;
                    }
                }
            }
        }
        System.out.println(count);
枯寂 2024-07-25 02:11:59

如果您需要原始字符串中每个子字符串的索引,您可以使用 indexOf 执行以下操作:

 private static List<Integer> getAllIndexesOfSubstringInString(String fullString, String substring) {
    int pointIndex = 0;
    List<Integer> allOccurences = new ArrayList<Integer>();
    while(fullPdfText.indexOf(substring,pointIndex) >= 0){
       allOccurences.add(fullPdfText.indexOf(substring, pointIndex));
       pointIndex = fullPdfText.indexOf(substring, pointIndex) + substring.length();
    }
    return allOccurences;
}

If you need the index of each substring within the original string, you can do something with indexOf like this:

 private static List<Integer> getAllIndexesOfSubstringInString(String fullString, String substring) {
    int pointIndex = 0;
    List<Integer> allOccurences = new ArrayList<Integer>();
    while(fullPdfText.indexOf(substring,pointIndex) >= 0){
       allOccurences.add(fullPdfText.indexOf(substring, pointIndex));
       pointIndex = fullPdfText.indexOf(substring, pointIndex) + substring.length();
    }
    return allOccurences;
}
胡渣熟男 2024-07-25 02:11:59
public static int getCountSubString(String str , String sub){
int n = 0, m = 0, counter = 0, counterSub = 0;
while(n < str.length()){
  counter = 0;
  m = 0;
  while(m < sub.length() && str.charAt(n) == sub.charAt(m)){
    counter++;
    m++; n++;
  }
  if (counter == sub.length()){
    counterSub++;
    continue;
  }
  else if(counter > 0){
    continue;
  }
  n++;
}

return  counterSub;

}

public static int getCountSubString(String str , String sub){
int n = 0, m = 0, counter = 0, counterSub = 0;
while(n < str.length()){
  counter = 0;
  m = 0;
  while(m < sub.length() && str.charAt(n) == sub.charAt(m)){
    counter++;
    m++; n++;
  }
  if (counter == sub.length()){
    counterSub++;
    continue;
  }
  else if(counter > 0){
    continue;
  }
  n++;
}

return  counterSub;

}

你丑哭了我 2024-07-25 02:11:59

???? Just a little more peachy answer

    public int countOccurrences(String str, String sub) {
        if (str == null || str.length() == 0 || sub == null || sub.length() == 0) return 0;
        int count = 0;
        int i = 0;
        while ((i = str.indexOf(sub, i)) != -1) {
            count++;
            i += sub.length();
        }
        return count;
    }
窝囊感情。 2024-07-25 02:11:59

刚才面试时被问到这个问题,我当时一片空白。 (像往常一样,我告诉自己,面试结束的那一刻我就会得到解决方案)我做到了,通话结束后 5 分钟:(

    int subCounter=0;
    int count =0;
    for(int i=0; i<str.length(); i++) {
        if((subCounter==0 && "a".equals(str.substring(i,i+1))) 
                || (subCounter==1 && "b".equals(str.substring(i,i+1)))
                || (subCounter==2 && "c".equals(str.substring(i,i+1)))) {
            ++subCounter;
        }
        if(subCounter==3) {
            count = count+1;
            subCounter=0;
        }
    }
    System.out.println(count);

I was asked this question in an interview just now and I went completely blank. (Like always, I told myself that the moment the interview ends ill get the solution) which I did, 5 mins after the call ended :(

    int subCounter=0;
    int count =0;
    for(int i=0; i<str.length(); i++) {
        if((subCounter==0 && "a".equals(str.substring(i,i+1))) 
                || (subCounter==1 && "b".equals(str.substring(i,i+1)))
                || (subCounter==2 && "c".equals(str.substring(i,i+1)))) {
            ++subCounter;
        }
        if(subCounter==3) {
            count = count+1;
            subCounter=0;
        }
    }
    System.out.println(count);
枕花眠 2024-07-25 02:11:59

这个问题的最佳解决方案可以在org.springframework.util.StringUtils.countOccurrencesOf(string, substring)中找到:

// IndexOfWithJumpSubstringCounterImpl (countOccurrencesOf after refactoring)
public static int count(String string, String substring) {
    if (string == null || string.length() == 0 
        || substring == null || substring.length() == 0) {
        return 0;
    }

    int count = 0;
    int idx;
    for(int pos = 0; (idx = string.indexOf(substring, pos)) != -1; pos = idx + substring.length()) {
        ++count;
    }

    return count;
}

有基于JMH的性能比较(完整报告:https://medium.com/p/d924cf933fc3):

(impl)                                Mode  Cnt      Score     Error   Units
IndexOfWithJumpSubstringCounterImpl  thrpt   10  86171.752 ± 225.064  ops/ms
IndexOfSubstringCounterImpl          thrpt   10  77560.418 ± 154.745  ops/ms
ReplaceBasedSubstringCounterImpl     thrpt   10  29758.761 ±  35.899  ops/ms
RegExSubstringCounterImpl            thrpt   10   5121.197 ±  10.030  ops/ms

The best solution to this problem you can find in org.springframework.util.StringUtils.countOccurrencesOf(string, substring):

// IndexOfWithJumpSubstringCounterImpl (countOccurrencesOf after refactoring)
public static int count(String string, String substring) {
    if (string == null || string.length() == 0 
        || substring == null || substring.length() == 0) {
        return 0;
    }

    int count = 0;
    int idx;
    for(int pos = 0; (idx = string.indexOf(substring, pos)) != -1; pos = idx + substring.length()) {
        ++count;
    }

    return count;
}

There is performance comparison based on JMH (full report: https://medium.com/p/d924cf933fc3):

(impl)                                Mode  Cnt      Score     Error   Units
IndexOfWithJumpSubstringCounterImpl  thrpt   10  86171.752 ± 225.064  ops/ms
IndexOfSubstringCounterImpl          thrpt   10  77560.418 ± 154.745  ops/ms
ReplaceBasedSubstringCounterImpl     thrpt   10  29758.761 ±  35.899  ops/ms
RegExSubstringCounterImpl            thrpt   10   5121.197 ±  10.030  ops/ms
耳钉梦 2024-07-25 02:11:59

抱歉,几乎所有答案都是未经优化的。 这是一道正确的算法题。
给定一个大小为 N 的字符串。包含来自某个集合 C 的字符。我们称这个集合为字母表。
给定任何大小为 M 的模式。包含来自同一集合 C 的字符。
然后有两种方法:
请查看

  1. Rabin-Karp 字符串匹配算法(更简单)
  2. Knuth Morris-Pratt 算法(复杂)
    两者的成本都在 = Thetha(N + M) 左右,但 KMP 在某些情况下表现更好。

Sorry almost all are unoptimized answers. This is a proper algorithm question.
Given a String of Size N. Containg characters from some set C. Lets call this set Alphabet.
Given any pattern of Size M. Containing characters from same set C.
Then 2 approaches :
Please look into

  1. Rabin-Karp String Matching algorithm (easier)
  2. Knuth Morris-Pratt Algorith (complex)
    Both Cost around = Thetha(N + M) but KMP performs better in some scenarios.
冷情妓 2024-07-25 02:11:59
   public static int countOrSubstring(String source, String substring) {
        if(source == null || substring == null || source.isEmpty() || substring.isEmpty()) return 0;
        var count = 0;
        for(var i = source.indexOf(substring);i>=0;i=source.indexOf(substring,i+substring.length())) count++;
        return count;
    }
   public static int countOrSubstring(String source, String substring) {
        if(source == null || substring == null || source.isEmpty() || substring.isEmpty()) return 0;
        var count = 0;
        for(var i = source.indexOf(substring);i>=0;i=source.indexOf(substring,i+substring.length())) count++;
        return count;
    }
荒芜了季节 2024-07-25 02:11:58

如何使用 StringUtils.countMatches 来自 Apache Commons Lang?

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));

输出:

3

How about using StringUtils.countMatches from Apache Commons Lang?

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));

That outputs:

3
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文