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

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()
相关推荐
圆山猫5 小时前
[Virtualization](四):Linux KVM/RISC-V 的 vCPU 运行路径
java·linux·risc-v
微学AI5 小时前
一根针指向所有方向:挂谷猜想对 LLM Agent 技能-记忆架构的启示
开发语言·人工智能·架构·挂谷猜想
城管不管5 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
IT小白杨5 小时前
从环境制备到自动化工作流:多账号运营的工程化架构拆解
java·经验分享·自动化·安全架构·指纹浏览器
豆瓣鸡6 小时前
算法日记 - Day3
java·开发语言·算法
萧瑟余晖6 小时前
Java深入解析篇九之NIO详解
java·网络·nio
韭菜炒鸡肝天6 小时前
VTK开发笔记(一):VTK介绍,Qt..+VSx+VTK.编译
开发语言·笔记·qt
The Chosen One9856 小时前
高进度算法模板速记(待完善)
java·前端·算法
Aaron - Wistron7 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
Dxy12393102168 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python