1 #define _CRT_SECURE_NO_WARNINGS 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 int main() 6 { 7 8 /* 9 字符串的赋值: 10 给 char* 类型的字符串赋值,可以直接使用 "=" 号 11 给 char[] 类型的字符串赋值,需要使用 strcpy 函数 12 13 字符串的特点: 14 需要明白的一点就是字符串以 结尾, 没有 就不是字符串 15 只要是用双引号括起来的都是字符串 16 字符串的本质就是数组(字符数组) 17 */ 18 19 /* 20 输入: 21 利用scanf函数接收字符串 22 利用gets函数接收字符串 23 利用fgets函数接收字符串(推荐常用!) 24 */ 25 printf("请输入一个字符串:"); 26 char name[12]; 27 //scanf("%s", name);//利用scanf函数接收字符串,会以空格、Tab、回车 作为结束符 28 29 //gets(name);//利用gets函数接收字符串,可以输入空格、Tab,以回车作为结束符; 30 //不安全,输入字符串没有长度限制,无限输入会造成内存溢出 31 32 fgets(name, 12, stdin); 33 //解决了安全性问题 34 //fgets(参数1,参数2, 参数3) 35 //参数1:保存数据的首位置 36 //参数2:保存的长度(包括 ' ') 37 //参数3:stdin(标准控制台输入) 38 //接收空格、Tab,以回车作为结束符 39 40 printf("name = %s ", name); 41 42 /* 43 输出: 44 %s的原理, 从传入的"地址"开始逐个取出, 直到遇到" "位置 45 46 如何输出字符串: 47 使用printf的%s占位符来输出 48 使用puts函数来输出(自动换行,原样输出) 49 */ 50 51 char str[] = "how are you"; 52 printf("%s ", str); // 使用printf的%s占位符来输出 53 54 puts(str);//使用puts函数来输出(自动换行,原样输出) 55 56 system("pause"); 57 return 0; 58 }
1 #include <stdio.h> 2 #include <stdlib.h> 3 // 数组赋值三种方式 4 5 void mystrcpy(char *str1, const char *str2) 6 { 7 // *str2对*str1逐个字符进行赋值 8 // *str2直到把' '赋值给*str1时,*str1的结果就是0,循环就结束! 9 while ((*str1++ == *str2++)); 10 11 } 12 13 int main() 14 { 15 char str[10] = "abc"; 16 17 // 使用循环给字符数组赋值 18 for (int i = 0; i < 10; i++) 19 { 20 str[i] = "ABC"[i]; // 等价于 *("ABC"+i),"ABC"返回的是A的地址(即首地址)==> 替换 21 printf("%s ", str); //str = ABC 22 } 23 24 // 使用标准库函数给字符数组赋值 25 strcpy(str, "XYZ"); 26 printf("str = %s ", str); 27 28 // 使用自定义函数给字符数组赋值 29 mystrcpy(str, "OKOK"); 30 printf("str = %s ", str); 31 32 33 system("pause"); 34 return 0; 35 }
1 // 库函数 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 6 int main() 7 { 8 // 计算字符串的长度(strlen):(计算字符串中有多少个字符,注意不包括 ) 9 // strlen的原理 : 从传入的地址开始逐个取出字符串, 每取出一个就让计数器 + 1.直到遇到 为止。 10 11 char str[] = "how are you"; // 定义字符数组 12 13 int len = sizeof(str) / sizeof(str[0]) - 1; 14 printf("%d ", len); 15 //printf("%d ", strlen(str)); // 计算结果不包括 16 17 //字符串拼接(strcat) 18 //原理 : 首先遍历第一个字符串, 直到遇到 为止, 19 //然后取出第二个字符串中的字符, 从 的位置开始添加, 添加完毕之后再在最后添加一个 20 void Strcat(char *s1, char *s2) 21 { 22 // 找位置 23 while (*s1) s1++; 24 25 // 拷贝 26 while(*s1++ = *s2++) 27 } 28 29 // 字符串拷贝(strcpy) 30 // strcpy函数会将源的数据拷贝到目标中, 31 // 并且会覆盖掉目标中原有的数据,目标的容积必须能够存放拷贝的数据, 如果容积不够会报错。 32 33 void Strcpy(char *s1, char *s2) 34 { 35 while (1) 36 { 37 *s1 = *s2; 38 if (*s1 == '