字符串强化训练
- 字符串是有标志的
利用三种方式对字符串进行拷贝
- 利用[]
- 利用指针
- 利用while(*dest++=*source++){}
代码示例:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void test01()
{
//注意字符串需要有结束标志
char str1[] = {
'h','e','l','l','o','\0'};
printf("%s\n",str1);
//字符数组部分初始化,剩余填0
char str2[100] = {
'h','e','l','l','o'};
printf("%s\n",str2);
//如果以字符串初始化,那么编译器默认会在字符串尾部添加‘\n’
char str3[] = "hello";
printf("%s\n",str3);
printf("sizeof str:%d\n",sizeof(str3));
printf("strlen str:%d\n",strlen(str3));
//sizeof计算数组大小,数组包含'\0'字符
//strlen计算字符串的长度,到'\0'结束
char str4[100] = "hello";
printf("sizeof str:%d\n",sizeof(str4));
printf("strlen str:%d\n", strlen(str4));
char str5[] = "hello\0world";
printf("%s\n",str5);
printf("sizeof str5:%d\n", sizeof(str5));//12
printf("strlen str5:%d\n", strlen(str5));//5
char str6[] = "hello\012world";//\012是八进制 下转十进制的10,在ASCII表中是换行
printf("%s\n",str6);
printf("sizeof str6:%d\n", sizeof(str6));//12
printf("strlen str6:%d\n", strlen(str6));//11
}
//字符串拷贝
//参数1 目标字符串 参数2 源字符串
//需求 将原字符串中的内容 拷贝到目标字符串中
void copyString01(char*dest, char*source)
{
int len = strlen(source);
for (int i = 0; i < len; i++)
{
dest[i] = source[i];
}
dest[len] = '\0';
}
//第二种 利用字符串指针进行拷贝
void copyString02(char*dest, char*source)
{
while (*source!='\0')
{
*dest = *source;
dest++;
source++;
}
*dest = '\0';
}
//第三种方式
void copyString03(char*dest, char*source)
{
while (*dest++=*source++){
}
//int a = 0;
//while (a=0)
//{
// printf("a");
//}
}
void test02()
{
char *str = "hello world";
char buf[1024];
//copyString01(buf,str);
//copyString02(buf, str);
copyString03(buf,str);
//printf("%s\n", buf);
}
int main()
{
//test01();
test02();
return EXIT_SUCCESS;
}
更多文章,敬请关注微信公众号:YQ编程