第十章 字符串习题
10-0、字符串
(1)字符串变量
(2)char* s = “hello,world!”;
(3)char*是字符串吗?
(4)char**a
(5) putchar
(6)gatchar
#include <stdio.h>
int main(int argc, char const *argv[])
{
int ch;
while( (ch = getchar()) != EOF ){
putchar(ch);
}
return 0;
}
10-1、 字符串函数strlen
计算字符串长度
#include <stdio.h>
#include <string.h>
size_t strlen(const char* s)//字符串函数
{
int idx = 0;
while (s[idx] != '\0'){//字符串总长不包含字符'0'
idx++;
}
return (idx+1);//1是字符'0'
}
int main(int argc, char const *argv[])
{
char line[] = "hello";
printf("strlen = %lu\n", strlen(line));//字符串函数计算字符串长度
printf("sizeof = %lu\n", sizeof(line));//sizeof计算字符串长度
return 0;
}
10-2、 字符串函数strcmp
比较两个字符串
#include <stdio.h>
#include <string.h>
//字符串函数,比较两个字符串,并将差值返回
int mycmp(const char* s1, const char* s2)
{
//方法一
while (*s1 == *s2 && *s1 != '\0'){//字符串结尾标志字符:'0'
s1++;
s2++;
}
return *s1 - *s2;
// {//方法二
// int idx = 0;
// while (s1[idx]==s2[idx] && s1[idx]!='\0'){//字符串结尾标志字符:'0'
// idx++;
// }
// return s1[idx] - s2[idx] ;
// }
// {//方法三
// int idx = 0;
// while (1){
// if(s1[idx] != s2[idx]){
// break;
// } else if(s1[idx] == '\0'){
// break;
// }
// idx++;
// }
// return s1[idx] - s2[idx] ;
// }
}
int main(int argc, char const *argv[])
{
char s1[] = "abc";
char s2[] = "Abc";
printf("%d\n", mycmp(s1,s2));
printf("%d\n", 'a'-'A');
return 0;
}
10-3、字符串函数strcpy
复制一个字符串
#include <stdio.h>
#include <string.h>
//字符串函数, 将s2的内容复制到s1
char* strcpy(char* dst, const char* src)
{
//方法一 ,数组
int idx = 0;
while(src[idx]){//src[idx]等价 src[idx] != '\0'
dst[idx] = src[idx];
idx++;
}
dst[idx] = '\0';
return dst;
//方法二,指针
// char* ret = dst;
// while( *src ){//*src等价*src != '\0'
// *dst++ = *src++;
// }
// *dst = '\0';
// return ret;
}
int main(int argc, char const *argv[])
{
char s1[] = "abc";
char s2[] = "Abc";
strcpy(s1,s2);
printf("%s\n",s1);
printf("%s\n",s2);
return 0;
}
10-4、字符串函数strcat
10-5、strcat-strcpy-strcmp安全版本
10-6、字符串中找字符-strchr
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char s[] = "hello";
{//找第一个'l'
// char *p = strchr(s,'l');
// printf("%s\n",p);
//找第二个'l'
// p = strchr(p+1,'l');
// printf("%s\n",p);
}
{//将s[]里的'llo'拷贝到另一个字符串里
// char *p = strchr(s,'l');
// char *t = (char*)malloc(strlen(p)+1);//申请内存空间,长度为llo+\0=4
// strcpy(t,p);//拷贝
// printf("%s\n",t);
// free(t);//释放空间
}
{//将s[]里的'he'拷贝到另一个字符串里
char *p = strchr(s,'l');
char c = *p;//此时c = 'l'
*p = '\0'; //将s中第一个'l'改为'\0',即s 此时为 h e \0 l o
char *t = (char*)malloc(strlen(s)+1);//申请内存空间,长度为llo+\0=4
strcpy(t,s);//拷贝
*p = c; //恢复,将s中第的'\0'改为'l',即s 此时为 h e l l o
printf("%s\n",t);
free(t);//释放空间
}
return 0;
}
- strchr:寻找单个字符。
- strstr:寻找一个字符串。
- strcasestr:寻找字符串时,忽略大小写。