一、字符串操作主要包括字符串复制、字符串比较和字符串拼接

    1、定义:字符串复制strcpy,字符串比较strcmp、字符串拼接strcat

    2、特征:

      1)、必须包含头文件string.h

      2)、具体可以通过man 3 strcpy、man 3 strcmp、man 3 strcat帮助文件,查看具体用法

      3)、输出字符串的内容是在printf函数中,使用%s的占位符,后面,只要之处字符串的首地址即可
      
    3、字符串赋值strcpy:

  #include <stdio.h>
#include <stdlib.h>
#include <string.h> int main(int argc, char **argv)
{
char *ptrArr1 = (char *)malloc(sizeof(char) * );
strcpy(ptrArr1, "guochaoteacher");
printf("ptrArr1: %s\n", ptrArr1); char *ptrArr2 = (char *)malloc(strlen("guochaoteacher") + );
strcpy(ptrArr2, "guochaoteacher");
printf("ptrArr2: %s\n", ptrArr2); return ;
}

      1)、为字符串申请内存空间,可以使用第7行的形式,直接指定字节大小,这种是做法是不安全的

      2)、为字符串申请内存空间,可以使用第11行的形式,使用strlen函数确定需要的字节大小,切记字符串的结束符'\0'是需要一个字节的,这种是做法是安全的

      3)、使用strcpy函数将第二个参数的内容复制到第一个参数中
  

    4、字符串比较strcmp:

  #include <stdio.h>
#include <stdlib.h>
#include <string.h> int main(int argc, char **argv)
{
char *command = (char *)malloc(sizeof(char) * );
printf("please input command: ");
scanf("%s", command);
printf("command: %s\n", command);
if(strcmp(command, "Quit") == || strcmp(command, "quit") == ){
printf("You input the command: %s", command);
}else{
printf("You can't quit!\n");
} return ;
}

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

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

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

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

  #include <stdio.h>
#include <stdlib.h>
#include <string.h> int main(int argc, char **argv)
{
char *ptrArr1 = (char *)malloc(sizeof(char) * );
ptrArr1 = "Hello";
printf("ptrArr1: %s and %p\n", ptrArr1, ptrArr1);
char *ptrArr2 = (char *)malloc(sizeof(char) * );
strcat(ptrArr2, ptrArr1);
printf("ptrArr2: %s and %p\n", ptrArr2, ptrArr2);
strcat(ptrArr2, " World!");
printf("ptrArr2: %s and %p\n", ptrArr2, ptrArr2); return ;
}

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

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

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

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

最新文章

  1. [LeetCode] Palindrome Partitioning II 拆分回文串之二
  2. pandas 学习(1): pandas 数据结构之Series
  3. 扁平设备树(FDT)
  4. [XAF] How to set List View Columns Title Customization align center?
  5. git注意
  6. kill 非法用户
  7. jQuery选择器(适合初学者哟....)
  8. 365. Water and Jug Problem
  9. URAL 1297 Palindrome(后缀数组+ST表)
  10. 认识Backbone (二)
  11. PHP的魔法方法
  12. JavaScript 函数创建思想
  13. 线段树 (区间查询最大 区间求和 区间加)带lazy
  14. DOM生成XML文档
  15. Django中间件2
  16. 怎么将XML字符串转换为XmlDocument,并获取部分节点值
  17. Jquery/js引入的button的onclik事件只触发一次
  18. 关于KMP
  19. php连接oracle数据库
  20. JQUERY框架的优点与面试题

热门文章

  1. 关于C与C++的区别
  2. NOIP2018 - 暑期博客整理
  3. 【线程池】ExecutorService与quartz搭配出现的问题
  4. 【php】php安全问题
  5. Thinkphp5 的常用连式查询
  6. LeetCode(287)Find the Duplicate Number
  7. 全套Office办公软件WORD/PPT/EXCEL视频教程 每日更新中
  8. python中用exit退出程序
  9. ubuntu检测到系统错误解决方法
  10. WebService的简介, 原理, 使用,流程图