计算字符串中子串的个数

本文介绍了一个Java程序示例,演示了如何使用indexOf方法在主字符串中查找子字符串,并计算子字符串出现的次数。通过Scanner类读取输入,利用while循环遍历字符串,直至找不到子字符串为止。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package work;

import java.util.Scanner;

public class A48 {
	public static void main(String[] args)
	{
		String str1;//字符串
		String str2;//子字符串
		int ans=0,start=0;
		Scanner cin =new Scanner(System.in);
		str1=cin.nextLine();
		str2=cin.nextLine();
		while(str1.indexOf(str2,start)>=0&&start<str1.length())//当字符串出现子串时,返回字符串索引
		{
			ans++;
			start=str1.indexOf(str2,start)+str2.length();
		}
		System.out.println(ans);
		
	}

}

 indexOf的用法:返回第一次找到的字符串子串的位置,若存在子串,则返回值为0,否则,返回-1.

 

 

在C语言中,查找字符串中子字符串个数通常可以使用KMP算法(Knuth-Morris-Pratt算法)或者Rabin-Karp算法等高级搜索算法,因为直接遍历可能会有较高的时间复杂度。以下是使用KMP算法的一个简单示例: ```c #include <stdio.h> #include <string.h> void compute_lps(char* pattern) { int len = strlen(pattern); int lps[len]; lps[0] = 0; int index = 1; while (index < len) { if (pattern[index] == pattern[lps[index - 1]]) { lps[index] = lps[index - 1] + 1; index++; } else { if (lps[index - 1] != 0) { index = lps[index - 1] + 1; } else { lps[index] = 0; index++; } } } for (int i = 0; i < len; i++) { printf("%d ", lps[i]); } } int kmp_count_substrings(char* text, char* pattern) { compute_lps(pattern); // 计算模式的最长公共前后缀数组 int count = 0; int n = strlen(text), m = strlen(pattern); int i = 0, j = 0; while (i < n) { if (text[i] == pattern[j]) { // 如果当前字符匹配 i++; j++; if (j == m) { // 找到一个完整匹配 count++; j = lps[j - 1]; // 如果模式结束,跳回LPS对应的字符 } } else if (j > 0) { // 如果当前不匹配,尝试从LPS开始回溯 j = lps[j - 1]; } else { // 如果模式的第一个字符不匹配,向右移动文本指针 i++; } } return count; } int main() { char str[] = "Hello World, Hello Universe"; char patt[] = "Hello"; int sub_count = kmp_count_substrings(str, patt); printf("Substring '%s' appears %d times in the string.\n", patt, sub_count); return 0; } ``` 在这个例子中,`kmp_count_substrings`函数会返回给定字符串中子`pattern`出现的次数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值