字符串中的子串数 [英] Count of substrings within string

查看:160
本文介绍了字符串中的子串数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序应该执行以下操作:

My program should do the following:


  1. 用户输入字符串:科迪勒拉斯大学

  2. 用户输入子字符串:er

  3. 程序输出子字符串数:2(Univ er 的Cordill er 为)

  1. User enters a string: University of the Cordilleras
  2. User enters the substring: er
  3. Program outputs the substring-count: 2 (University of the Cordilleras)

我不应该使用.str,而是创建我自己的方法。

I should not use .str, but create my own method.

推荐答案

只需替换第一个匹配项并计数直到没有。

Just replace the first occurrence and count until there is none.

int count = 0;
while (str.indexOf(subStr)>-1){
    str = str.replaceFirst(subStr, "");
    count++;
}
return count ;

这篇关于字符串中的子串数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆