编写函数计算字符串中子串出现的次数

C语言 码拜 9年前 (2015-07-10) 1518次浏览 0个评论

1、 编写函数计算字符串中子串出现的次数,如“abcdefabcdefabcdef”中出现子串“cde”三次(不允许使用标准库函数子串查找功能)。主函数实现输入字符串、输出字符串以及调用计算子串出现次数函数步骤。

2、 编写函数实现以下功能:有n个整数,使其前面各数顺序向后移m个位置,直至最后m个数变成最前面的m个数。主函数实现输入整数、输出整数及调用整数移位函数步骤。

麻烦写一下代码注释,如果有运算截图更好。麻烦会的帮帮忙,非常感谢!!!!

20分

必须给你解决它:
第一题

#include <stdio.h>
#include <string.h>
int *next;
void setNext(char *p, int *next)
{
	int j, k, len;
	len = strlen(p);
	j = 1;
	next[0] = -1;
	while (j < len)
	{
		k = next[j - 1];
		while (k >= 0 && p[j - 1] != p[k])
			k = next[k];
		if (k >= 0) next[j] = k + 1;
		else next[j] = 0;
		j++;
	}
}
int kmp(char *t, char *p)
{
	if (NULL == t || NULL == p) return -1;
	int len1, len2, r;
	len1 = strlen(t), len2 = strlen(p);
	len1 = strlen(t);
	len2 = strlen(p);
	if (len1 >= len2)
	{
		int i, j, k;
		i = j = -1;
		k = len1 - len2;
		while (i <= k && j < len2)
		{
			if (-1 == j || t[i] == p[j])
			{
				i++;
				j++;
			}
			else j = next[j];
		}
		if (len2 == j) return i - j;
		else return -1;
	}
	return -1;
}
int main(void)
{
	int count = 0;
	char t[] = "abcdefabcdefabcdef";
	char p[] = "cde";
	int lenp = strlen(p);
	next = malloc(sizeof(int)*lenp);
	setNext(p, next);
	char *q = t;
	while (-1 != kmp(q, p))
	{
		q += strlen(p);
		count++;
	}
	printf("字符串%s在字符串%s中出现的次数是%d\n", p, t, count);
	free(next);
	return 0;
}

20分

第二题

#include <stdio.h>
void print(int *arr, int n)
{
	int i;
	for (i = 0; i < n; i++) printf("%3d", arr[i]);
	printf("\n");
}
int main(void)
{
	int arr[] = { 1,2,3,4,5 };
	int n = sizeof(arr) / sizeof(int);
	print(arr, n);
	int m = 2;   //把后m个数移动到前面
	int i, j;
	i = n - 1, j = n - 1 - m;
	int t = arr[i];
	while (j != n - 1)
	{
		arr[i] = arr[j];
		i = j;
		j = (j - m + n) % n;
	}
	arr[i] = t;
	print(arr, n);
	return 0;
}
//  1  2  3  4  5
//  4  5  1  2  3
 

非常感谢!!!!!!

 
java的好简单
HashMap<String, Integer> map = new HashMap<>();
String key;
for (int i = 0; i < str.length(); i++) {
for(int j=i+1;j<str.length();j++){
key = str.substring(i,j);
if(!map.containsKey(key)){
map.put(key, 1);
}else{
map.put(key, map.get(key)+1);
}

}
}


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明编写函数计算字符串中子串出现的次数
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!