32深入理解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函数将第二个参数的内容复制到第一个参数中
  

    4、字符串比较strcmp:

 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)、为字符串申请内存空间,可以使用安全和不安全的方式,如果不能确定就将空间设置的足够大也可;

      2)、使用strcmp函数时,将会比较第一个参数和第二个参数在字典中的位置,若第一个小,返回负数,大就返回正数,否则为零;

      3)、使用strcmp函数比较的是两个参数中的内容;

      4)、使用==比较的是两个参数中的地址,即使内容完全一样,结果也可能是否定的;
  
    5、字符串拼接strcat:

 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 }


      1)、字符串使用前,记得一定要提前申请内存空间;

      2)、使用strcat函数将第二个参数的内容拼接到第一个参数中

      3)、在strcat函数中,第一参数需要有足够的空间放置拼接后的内容

      4)、在strcat函数中,第二参数可以是具体的字符串字面量,也可以是指针

posted @ 2017-06-08 06:37  叕叒双又  阅读(456)  评论(0编辑  收藏  举报