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

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()
相关推荐
编程彩机1 小时前
互联网大厂Java面试:从分布式架构到大数据场景解析
java·大数据·微服务·spark·kafka·分布式事务·分布式架构
青岑CTF1 小时前
攻防世界-Ics-05-胎教版wp
开发语言·安全·web安全·网络安全·php
Li emily1 小时前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股
小酒窝.1 小时前
【多线程】多线程打印1~100
java·多线程
君爱学习1 小时前
基于SpringBoot的选课调查系统
java
APIshop2 小时前
Java 实战:调用 item_search_tmall 按关键词搜索天猫商品
java·开发语言·数据库
血小板要健康2 小时前
Java基础常见面试题复习合集1
java·开发语言·经验分享·笔记·面试·学习方法
淼淼7632 小时前
安装jdk1.8
java·开发语言
PfCoder2 小时前
WinForm真入门(23)---PictureBox 控件详细用法
开发语言·windows·c#·winform
Legendary_0082 小时前
Type-C 一拖二快充线:突破单口限制的技术逻辑
c语言·开发语言