计算一个字符串在另一个字符串中出现次数
·
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代码
#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()
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐


所有评论(0)