字符串查(两种⽅式)
1 #include <stdio.h>
2 #include <strings.h>
3/*******************
4 * 头⽂件:#include <strings.h>
5 * 函数:char *index(const char *s, int c);
6 * 功能:从已有字符串中查⼀个字符所在当前字符串的位置
7 * 参数:
8 * s:原字符串
9 * c:要查的字符
10 * 返回值:
11 * 成功返回:⾮NULL的地址(在查的字符串中到字符的地址(索引))
12 * 失败返回:NULL
13 * **********************************************************/
14int main()
15 {
16char buf[120] = "abcdef sdcbdwd asdbfnwe";
17char *p = NULL;
18 p = index(buf,'c');
19if(p == NULL)
20 {
21 printf("查值不存在\n");
22 }
23else
24 {
25 printf("p = %s\n",p);
26 }
字符串长度查询27
28 p = index(p+1,'c');
29if(p == NULL)
30 {
31 printf("查值不存在\n");
32 }
33else
34 {
35 printf("p = %s\n",p);
36 }
37
38return0;
39 }
1 #include <string.h>
2 #include <stdio.h>
3/*******************
4 * 头⽂件:#include <string.h>
5 * 函数:char *strstr(const char *haystack, const char *needle);
6 * 功能:从已有字符串中查⼀个字符串所在当前字符串的位置
7 * 参数:
8 * haystack:原字符串
9 * needle:要查的字符串
10 * 返回值:
11 * 成功返回:⾮NULL的地址(在查的字符串中到字符串的地址(索引))
12 * 失败返回:NULL
13 * **********************************************************/
14int main()
15 {
16char buf[1024] = "123456789012345678901234567890";
17char *p = NULL;
18 p = strstr(buf, "5678");
19if (p == NULL)
20 {
21 printf("查值不存在\n");
22 }
23else
24 {
25 printf("p = %s\n", p);
26 }
27
28while (p != NULL)
29 {
30 p = strstr(p+1, "5678");
31if (p == NULL)
32 {
33 printf("查值不存在\n");
34 }
35else
36 {
37 printf("p = %s\n", p);
38 }
39 }
40
41return0;
42 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论