TA的每日心情 | 开心 2014-6-18 08:29 |
---|
签到天数: 14 天 [LV.3]偶尔看看II
滴水大师
 
- 积分
- 2345
|
题目
解决代码及点评
- <pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"></pre><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code">/*
- 功能:写一函数完成查找串s2在串s1中第一次出现的位置
-
- */
-
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
-
- int search(char *, int, char *, int); //查找第一次出现的位置,返回下标
-
- void main()
- {
- char s1[] = "fj12eia123fjoae;if123";
- char s2[] = "123";
-
- int n1 = strlen(s1);
- int n2 = strlen(s2);
-
- int pResult = search(s1,n1,s2,n2);
- if (pResult == -1)printf("NO");
- else
- {
- printf("start from s1[%d]",pResult);
- }
- system("pause");
- }
-
- int search(char *p1, int n, char *p2, int m) //n为p1的长度,m为p2的长度
- {
- int t = -1; //t为下标,初始化为-1, -1就是找不到
- for (int i = 0; i < n - m -1; i++) //遍历p1,找到与*p2相同的元素
- {
- if (p1 == p2[0])
- {
- t = i; //将i的下标存到t中
- int jj = 0;
- for (int j = 0; j < m; j++)
- {
- if (p1[i + j] != p2[j])
- break;
- jj++; //jj等于m时表示已经找到
- }
- if (jj == m)break;
- }
- }
- return t;
- }</pre></pre></pre>
|
|