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