早教吧 育儿知识 作业答案 考试题库 百科 知识分享

2、编写函数求字符串的子串,在主函数中输入子串作为参数,字符串长度不超过255.例如:由键盘依次输入字符串为WhatisbusNamesomebuses.LocalbusisahighspeedI/Obusclosetotheprocesser.主函数接收

题目详情
2、 编写函数求字符串的子串,在主函数中输入子串作为参数,字符串长度不超过255.
例如:由键盘依次输入字符串为 What is bus Name some buses.Local bus is a high speed I/O bus close to the processer.
主函数接收子串参数为" bus",子函数查找字符串中” bus”出现的次数返回给主函数.(不允许使用库函数substr)
▼优质解答
答案和解析
int substr1(char *str,char *sub)
{
int lenstr = strlen(str);
int lensub = strlen(sub);
int count = 0;
for (int i = 0; i < lenstr; i++)
{
if (str[i] == sub[0])
{
int j = 0;
for (; j < lensub; j++)
{
if (str[i + j] != sub[j])
break;
}
if (j == lensub)
{
count++;
i+=(j - 1);
}
}
}
return count;
}
int main(int argc,_TCHAR* argv[])
{
char str[255] = { 0 };// "What is bus Name some buses.Local bus is a high speed I/O bus close to the processer.";
printf("input string\n");
gets(str);
printf("input sub string\n");
char sub[255] = { 0 };
gets(sub);
printf("sub string appera %d times!\n",substr1(str,sub));
return 0;
}