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

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()
相关推荐
励志的小陈3 分钟前
贪吃蛇(C语言实现,API)
c语言·开发语言
QC班长13 分钟前
Maven公司私库配置踩坑点
java·服务器·maven·intellij-idea
Makoto_Kimur16 分钟前
java开发面试-AI Coding速成
java·开发语言
laowangpython18 分钟前
Gurobi求解器Matlab安装配置教程
开发语言·其他·matlab
wengqidaifeng22 分钟前
python启航:1.基础语法知识
开发语言·python
观北海25 分钟前
Windows 平台 Python 极简 ORB-SLAM3 Demo,从零实现实时视觉定位
开发语言·python·动态规划
wuqingshun3141591 小时前
说说mybatis的缓存机制
java·缓存·mybatis
空中海1 小时前
Kubernetes 生产实践、可观测性与扩展入门
java·贪心算法·kubernetes
Devin~Y1 小时前
大厂Java面试实录:Spring Boot/Cloud、Kafka、Redis、K8s 与 Spring AI(RAG/Agent)三轮连环问
java·spring boot·redis·mysql·spring cloud·kafka·kubernetes
bLEd RING2 小时前
SpringBoot3.3.0集成Knife4j4.5.0实战
java