为什么什么结果也没有啊

来源:百度知道 编辑:UC知道 时间:2024/06/01 04:29:46
#include<stdio.h>

void main()
{
char* str="asd asasdfg asd as zx67 asd mklo";
char* substr="as";
int k=0;
while(*str)
{
char*m=str,*n=substr;
while(*n)
{
if(*m==*n)
{
m++;n++;
}
else{break;}
}
if(*n=='\0')
{k++;str++;}
}
printf("%d",k);
}
为什么什么结果也没有呢???

关键是这句
str++;
放在if(*n=='\0') 内的话,找到才会往下找,
这样没找到的话,就一直在原地找,死循环了
你应该放到外面
像这样
if(*n == '\0') {
k++;
}
str++;

如果你用函数
char * strstr(const char *, const char *)
的话会简单一点
#include <stdio.h>
#include <string.h>

void main() {
char* str="asd asasdfg asd as zx67 asd mklo";
char* substr="as";
int k=0;

while( str = strstr( str, substr ) ) {
k++;
str++;
}
printf("%d\n",k);
}

你的程序中代码就没要他做什么,还是你的意思没赋给他。

你是想在一个字串中找另一个字串么?
那找到你返回什么值。我看不出来。
如是想返回除了子串后的字符串,str++;} 也是不对的,他是常量,不能自加,