首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

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

2012-03-08 
请教C语言高手解惑!!!疑问已在每句?号标注,谢谢~~这是c plus primer 的答案,看不太懂,请高手解惑!!!问题在

请教C语言高手解惑!!!疑问已在每句?号标注,谢谢~~
这是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 */
}



[解决办法]
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++想后扫描

热点排行