计算一个字符串在另一个字符串中出现次数

java代码

java 复制代码
public class StringOccurrences {
    public static void main(String[] args) {
        String str1 = "这是一个字符串要测试字符串出现的次数";
        String str2 = "字符串";
        int count = 0;
        int index = str1.indexOf(str2);
        while(index!=-1){
            count++;
            index = str1.indexOf(str2,index+str2.length());
        }
        System.out.println(count);
    }
}

python代码

python 复制代码
#coding:utf-8
# 计算一个字符串在另一个字符串中出现次数
def stringoccurrences():
    str1 = "这是一个字符串要测试字符串出现的次数"
    str2 = "字符串"
    count = 0
    index = str1.find(str2)
    while(index!=-1):
        count+=1
        index = str1.find(str2,index+1)
    print(count)

if __name__ == '__main__':
    stringoccurrences()
相关推荐
froginwe112 小时前
Bootstrap5 表格
开发语言
前端不太难2 小时前
Navigation State 驱动的页面调试方法论
开发语言·前端·react.js
饕餮怪程序猿2 小时前
订单分批算法设计与实现:基于商品相似性的智能分拣优化(C++)
开发语言·c++·算法
Li_7695322 小时前
Redis —— (五)
java·redis·后端·spring
崇山峻岭之间2 小时前
Matlab学习记录05
开发语言·学习·matlab
狗狗摇屁屁2 小时前
JS手写防抖
开发语言·javascript·ecmascript
派大鑫wink2 小时前
【Day7】构造方法与 this 关键字:初始化对象的正确姿势
java·开发语言
智算菩萨2 小时前
实战:用 Python + 传统NLP 自动总结长文章
开发语言·人工智能·python
沐知全栈开发2 小时前
WebForms HashTable 深入解析
开发语言