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()