请教C语言高手解惑!!!疑问已在每句?号标注,谢谢~~

kamfun 2011-08-15 05:44:33
这是c plus primer 的答案,看不太懂,请高手解惑!!!问题在每句打上问号,谢谢!!
浏览次数:17次 悬赏分:15 | 离问题结束还有 14 天 18 小时 | 提问者:匿名

7.要求是:编写一个函数string_in(),它接受两个字符串指针参数。如果第二个字符串被包含在第一个字符串中,函数就返回被包含的字符开始的地址。例 如,string_in("hats","at")返回hats中a的地址,则,函数返回空指针。在一个使用循环语句为这个函数提供输入的完整程序中进行 测试。
/* Programming Exercise 11-7 */
#include <stdio.h>
#include <string.h>
#define LEN 20
char * string_in(const char * s1, const char * s2);
int main(void)
{
char orig[LEN] = "transportation";
char * find;

puts(orig);
find = string_in(orig, "port");
if (find)
puts(find);
else
puts("Not found");
find = string_in(orig, "part");
if (find)
puts(find);
else
puts("Not found");

return 0;
}


char * string_in(const char * s1, const char * s2)
{
int l2 = strlen(s2);??下面3句有什么用?
int tries; /* maximum number of comparisons */
int nomatch = 1; /* set to 0 if match is found */

tries = strlen(s1) + 1 - l2; //3次???port和part不是有四个字符吗?
if (tries > 0)
while (( nomatch = strncmp(s1, s2, l2)) && tries--) //strncmp(s1, s2, l2)搜索S1前12个字符串 ????tries--??不是只有3次吗?while不是很快退出循环????
s1++;??这句有什么用?是指向第一个字符地址?怎么实现??
if (nomatch)
return NULL;
else
return (char *) s1; /* cast const away */
}

...全文
96 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
yetming_huang 2011-08-15
  • 打赏
  • 举报
回复
strlen(s2) 得到s2长度
tries是S1除S2剩余的长度
tries--剩余长度减少

int strncmp(char *str1, char *str2, int maxlen);   
说明:比较字符串str1和str2的大小,如果str1小于str2,返回值就<0,反之如果str1大于str2,返回值就>0,如果str1等于str2,返回值就=0,maxlen指的是str1与str2的比较的字符数。此函数功能即比较字符串str1和str2的前maxlen个字符。

(( nomatch = strncmp(s1, s2, l2)) && tries--)判断匹配阿



s1指针开始是指字符窜头阿 s1++想后扫描

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧