字符串强化之字符串拷贝和字符串反转

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include

void test01(){
	//字符串需要有结束的标志 '\0'
	//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);

	//如果以字符串初始化,那么编译器默认会在字符串的尾部添加'\0'
	//char str3[] = "hello";
	//printf("%s\n",str3);
	//printf("sizeof str3=%d\n", sizeof(str3)); //6 统计'\0'
	//printf("strlen str3=%d\n",strlen(str3));  //5 不统计'\0'

	//char str4[100] = "hello";
	//printf("sizeof str4 = %d\n", sizeof(str4)); //100
	//printf("strlen str4 = %d\n", strlen(str4)); //5

	//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 是八进制,在十进制下在ASCII表中是换行
	printf("%s\n",str6);
	printf("sizeof str6 = %d\n", sizeof(str6));//12
	printf("strlen str5 = %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++){}
}

void test02(){
	char *str = "hello world";
	char buf[1024];
	//copyString01(buf, str);
	//copyString02(buf,str);
	copyString03(buf, str);
	printf("%s\n", buf);
}

//字符串反转
//第一种方式,利用[]饭庄
void reverseString01(char *str){
	int len = strlen(str);
	int start = 0; //起始的位置下标
	int end = len - 1;//结束的位置下标
	while (start

 

你可能感兴趣的:(C语言高级编程)