天天看點

32深入了解C指針之---字元串操作

深入了解C指針之---字元串操作

  一、字元串操作主要包括字元串複制、字元串比較和字元串拼接

    1、定義:字元串複制strcpy,字元串比較strcmp、字元串拼接strcat

    2、特征:

      1)、必須包含頭檔案string.h

      2)、具體可以通過man 3 strcpy、man 3 strcmp、man 3 strcat幫助檔案,檢視具體用法

      3)、輸出字元串的内容是在printf函數中,使用%s的占位符,後面,隻要之處字元串的首位址即可

      

    3、字元串指派strcpy:

1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4
 5 int main(int argc, char **argv)
 6 {
 7     char *ptrArr1 = (char *)malloc(sizeof(char) * 10);
 8     strcpy(ptrArr1, "guochaoteacher");
 9     printf("ptrArr1: %s\n", ptrArr1);
10
11     char *ptrArr2 = (char *)malloc(strlen("guochaoteacher") + 1);
12     strcpy(ptrArr2, "guochaoteacher");
13     printf("ptrArr2: %s\n", ptrArr2);
14
15     return 0;
16 }      

      1)、為字元串申請記憶體空間,可以使用第7行的形式,直接指定位元組大小,這種是做法是不安全的

      2)、為字元串申請記憶體空間,可以使用第11行的形式,使用strlen函數确定需要的位元組大小,切記字元串的結束符'\0'是需要一個位元組的,這種是做法是安全的

      3)、使用strcpy函數将第二個參數的内容複制到第一個參數中

  

1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4
 5 int main(int argc, char **argv)
 6 {
 7     char *command = (char *)malloc(sizeof(char) * 10);
 8     printf("please input command: ");
 9     scanf("%s", command);
10     printf("command: %s\n", command);
11     if(strcmp(command, "Quit") == 0 || strcmp(command, "quit") == 0){
12         printf("You input the command: %s", command);
13     }else{
14         printf("You can't quit!\n");
15     }
16
17     return 0;
18 }      
1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4
 5 int main(int argc, char **argv)
 6 {
 7     char *ptrArr1 = (char *)malloc(sizeof(char) * 15);
 8     ptrArr1 = "Hello";
 9     printf("ptrArr1: %s and %p\n", ptrArr1, ptrArr1);
10     char *ptrArr2 = (char *)malloc(sizeof(char) * 25);
11     strcat(ptrArr2, ptrArr1);
12     printf("ptrArr2: %s and %p\n", ptrArr2, ptrArr2);
13     strcat(ptrArr2, " World!");
14     printf("ptrArr2: %s and %p\n", ptrArr2, ptrArr2);
15
16     return 0;
17 }      

人就像是被蒙着眼推磨的驢子,生活就像一條鞭子;當鞭子抽到你背上時,你就隻能一直往前走,雖然連你也不知道要走到什麼時候為止,便一直這麼堅持着。