【发布时间】:2011-04-27 03:09:25
【问题描述】:
所以,我的任务是在给定字符串中查找子字符串的数量。我不能使用任何 C 库来完成这项任务。 stringExist 只能有 2 个字符串作为参数。
我的解决方案正在运行,但我觉得应该有一种更优雅的方式来完成这项任务。 解决方案 1: 事实证明,它无法正常工作
#include <stdio.h>
int stringExist(char string[], char s2[]);
int main(void){
char string[] = "strstrASDstrSTRst";
char s2[] = "str";
printf("Final result: %i\n",stringExist(string,s2));
return 0;
}
int stringExist(char string[], char s2[]){
/* I am aware that I can init all this values in one row */
int count = 0;
int size = 0;
int i = 0;
int temp = 0;
int result = 0;
while(s2[size]!='\0'){
size++;
}
while(string[i]!='\0')
{
if(string[i]==s2[0])
{
printf("Found first occurrence\n");
count=0;
while((temp=(string[i]==s2[count]))!=0)
{
count++;
if(size==count){
printf("Match\n");
result++;
break;
}
i++;
}
}
i++;
}
return result;
}
解决方案 2:
目前没有发现错误。
做了一点不同的字符串遍历,现在我不在比较字符循环中增加 i。
#include <stdio.h>
int stringExist(char string[], char s2[]);
int main(void){
char string[] = "bobobobojkhhkjjkhbo;klkl;bobo";
char s2[] = "bobo";
printf("Final result: %i\n",stringExist(string,s2));
return 0;
}
int stringExist(char string[], char s2[]){
int count = 0;
int size = 0;
int i = 0;
int c = 0;
int temp = 0;
int result = 0;
while(s2[size]!='\0'){
size++;
}
for(i=0;string[i]!='\0';i++){
if(string[i]==s2[0])
{
printf("Found first occurence at %i\n",i);
count = 0;
c = i;
while((temp=(string[c]==s2[count]))!=0)
{
printf("Count %i, I %i, current char: %c\n",count, c,string[c]);
count++;
if(size==count){
printf("Match\n");
result++;
break;
}
c++;
}
}
}
return result;
}
感谢您的建议, 生命力
【问题讨论】:
-
每次在 s1 中找到 s2 的第一个字符时,这将打印出“第一次出现”。
-
您的功能不工作。试试 'char string[] = "strstrASDstrSTRststr";'答案应该是 4。
-
谢谢 Dingo,我也发现了这个问题 =(...我想我在这里使用了错误的方法...呸,我没主意了。