我需要C中字符串的帮助
我是C语言的新手,我遇到了这个问题。有人能帮我回答吗我需要C中字符串的帮助,c,string,function,C,String,Function,我是C语言的新手,我遇到了这个问题。有人能帮我回答吗 尝试编写一个函数,其中包含两个都是字符串类型的参数。返回值告诉您第一个字符串是否是第二个参数字符串的子字符串 char *strstr(char *haystack, char *needle){ if (!needle[0]) return haystack; unsigned int i; while (*haystack){ while (haystack[0]!=needle[0])haystack++; i=1; whi
尝试编写一个函数,其中包含两个都是字符串类型的参数。返回值告诉您第一个字符串是否是第二个参数字符串的子字符串
char *strstr(char *haystack, char *needle){
if (!needle[0]) return haystack;
unsigned int i;
while (*haystack){
while (haystack[0]!=needle[0])haystack++;
i=1;
while (haystack[i] && needle[i] && haystack[i]==needle[i++]);
if (!needle[i]) return haystack;
else haystack+=i;
}
return haystack;
}
或优化版本:
参考文献
您希望使用函数strstrstr在c语言中查找子字符串。比如说-
char s1[] ="hello world";
char * s2;
s2 = strstr (str,"world"); // s2 will be null pointer if it is not the substring
// else s2 will point to first occurrence of substring
if(!s2)
// return true
else
// return false
您应该试着自己找出如何将字符串传递给函数:)必须:您尝试了什么?我们只能帮助你自己动手,兄弟/姐姐。启动你::谷歌strstr及其逻辑。请在提问之前付出你的努力。谷歌/必应是你学习字符串的助手。谢谢。它起作用了perfectly@Kaylo17:不客气!我不得不稍微修改一下程序,以便输入我想要的文本。这仍然正确吗?@Kaylo17:据我所知,是的。我的意思是,自从你上次发表评论以来,我还没有更新过它。所以,如果它当时对你有用,那么现在对你也应该有用,因为从那以后我再也没有碰过它我本想附加我的代码,但在粘贴之前我按了回车键。我的错。仍然不习惯Stackoverflow的布局
typedef int bool;
#define false 0
#define true 1
char s1[] ="hello world";
char * s2;
s2 = strstr (str,"world"); // s2 will be null pointer if it is not the substring
// else s2 will point to first occurrence of substring
if(!s2)
// return true
else
// return false