1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
// 字符串数组 字符串指针 #include <stdio.h> int main(int argc, char const *argv[]) { // 以下两种定义差别不大,区别在于heart是地址常量,head是一个变量 char heart[] = "I love Tillie!"; char *head = "I love Millie!"; // 变量可以++,常量不行 while(*(head) != '\0') { putchar(*(head++)); } // 允许 现在head指向数组heart,但是不会使I love Millie!字符串消失 // 除非已在别处保存了I love Millie! 否则这个字符串就无法访问了 head = heart; // 不允许 这种情况类似 3=x; 把变量赋值给常量 heart = head; getchar(); return 0; } // gets() puts() 以及读取用户输入要设置长度 #include <stdio.h> #define LEN 81 int main(int argc, char const *argv[]) { // 记住一定要定义长度(分配内存空间),否则读入的name可能会覆盖程序中的数据和代码 char name[LEN]; char * returnVal; puts("what's your name"); // gets() puts() 跟scanf("%s") printf("%s")效果类似 returnVal = gets(name); puts(name); // gets()返回用户输入字符串的地址,puts(returnVal)和puts(name)输出一样 puts(returnVal); printf("what's your name\n"); char name1[LEN]; scanf("%s", name1); printf("%s\n", name1); getchar(); getchar(); return 0; } // gets()不会检查预留储存区的长度 // 如果单行超过19个字符,会溢出到相邻内存 #include <stdio.h> int main(int argc, char const *argv[]) { char name[20]; // 如果gets出错返回一个空指针NULL // 空指针是一个地址,空字符是一个char类型的数据对象 // 数值上两者都可以用0表示,但它们的概念不同 // 下面循环方式既可以检查是否读到文件结尾,又可以读取一个值 // 比while((ch=getchar())!=EOF)方便 while(gets(name) != NULL) { puts(name); } return 0; } // fgets()在键盘输入中的使用 gets()存在溢出问题,所以fgets()更安全 #include <stdio.h> #define MAX 21 int main(int argc, char const *argv[]) { char name[MAX]; char * ptr; puts("Hi what's your name"); // fgets()可以避免gets()的数据溢出问题 // 但是它是为文件I/O而设计的,读取键盘输入时没有gets()方便,需要在第3个参数键入stdin ptr = fgets(name, MAX, stdin); puts(name); puts(ptr); return 0; } // strcat(str1,str2)合并字符串 // 如果第一个字符串的长度不够,合并完之后的字符串就会溢出到相邻的存储单元 // strncat(str1,str2,13) 13为允许合并的最大长度 #include <stdio.h> #include <string.h> int main(int argc, char const *argv[]) { char name[10]; char info[]=" I'm your father"; puts("please key your name"); gets(name); //将第2个字符串的一份拷贝添加到第一个字符串结尾 strcat(name, info); puts(name); puts(info); getchar(); return 0; } // strcmp(str1,str2)比较字符串大小 // strncmp(str1,str2,5)比较字符串前5个字符大小 // sprintf(formal,"%s...",str...)和printf()类似 一个接收到formal变量 一个输出 // str1=str2只是指针赋值,如果需要复制值可以使用strcpy(str1,str2) // 同样strcpy也存在溢出问题 可以使用strncpy(str1,str2,maxCopyLen) #include <stdio.h> #include <string.h> int main(int argc, char const *argv[]) { char test[20]; int x; x = 13; //数值赋值 strcpy(test, "hello world"); //字符串赋值 test = "hello world"; //语法错误 strcpy(test+6, "fuck"); //从第6个字符开始 此时test=hello fuck return 0; } |