C++ C 风格字符串与string类
2017-04-26 15:48
218 查看
一,C 风格字符串
a,定义C 风格字符串常量
b,对字符串的操作
C语言在string.h(在C++中为cstring)中提供了一些列字符串函数。
1,strcmp
strcmp函数比较两个字符串的大小,该函数接受两个字符串地址作为参数,这意味着参数可以是指针、字符串常量或字符数组名。如果两个字符串相同,函数返回0;如果第一个字符串大于第二个字符串,函数返回1;如果第一个字符串小于第二个字符串,函数返回-1。
2,strcat
把一个字符串连接到已有的一个字符串的后面。
输出结果
3,strcpy
复制一个字符串
输出结果
hello
4,比较C风格的字符串,应注意的问题
要判断字符数组中的字符串是否是"hello",下面的做法得不到我们想要的结果
请记住,数组名是数组的地址。同样,用引用括号括起来的字符串常量也是其地址。因此,上面的关系表达式并不是判断两个字符串是否相同,而是查看他们是否存储在相同的位置上。应当使用前面介绍的strcmp()函数来进行比较。
二,C++ string类
string类是在头文件string中定义的(注意:头文件string.h与cstring支持对C风格字符串进行操作的C库字符串函数,但不支持string类)
1,构造字符串
a,定义C 风格字符串常量
char *str1 = "hello world"; char str2[20] = "hello world"; //定义字符串数组 char *str3[2] = {"hello", "world"};
b,对字符串的操作
C语言在string.h(在C++中为cstring)中提供了一些列字符串函数。
1,strcmp
strcmp函数比较两个字符串的大小,该函数接受两个字符串地址作为参数,这意味着参数可以是指针、字符串常量或字符数组名。如果两个字符串相同,函数返回0;如果第一个字符串大于第二个字符串,函数返回1;如果第一个字符串小于第二个字符串,函数返回-1。
char *str1 = "hello world"; char *str2 = "hold the door"; strcmp(str1, str2);
2,strcat
把一个字符串连接到已有的一个字符串的后面。
char str1[20] = "hello"; char *str2 = "world"; cout<<strcat(str1, str2);
输出结果
helloworld
3,strcpy
复制一个字符串
char *str1 = "hello"; char str2[10]; strcpy(str2, str1); cout<<str2<<endl;
输出结果
hello
4,比较C风格的字符串,应注意的问题
要判断字符数组中的字符串是否是"hello",下面的做法得不到我们想要的结果
char *str = "hello"; str == "hello";
请记住,数组名是数组的地址。同样,用引用括号括起来的字符串常量也是其地址。因此,上面的关系表达式并不是判断两个字符串是否相同,而是查看他们是否存储在相同的位置上。应当使用前面介绍的strcmp()函数来进行比较。
二,C++ string类
string类是在头文件string中定义的(注意:头文件string.h与cstring支持对C风格字符串进行操作的C库字符串函数,但不支持string类)
1,构造字符串
//使用C风格的字符串初始化string对象 char *str = "hello"; string one(str); string two("world"); //创建一个包含n个元素的string对象,其中每个元素都被初始化为字符c string three(10, 'k'); //使用一个string对象,初始化另一个string对象 string four(three); //创建一个默认的string对象,长度为0 string five;
相关文章推荐
- C++风格的字符串string类
- C++ Primer Plus 学习笔记 第五章 01 for循环 递增运算符和递减运算符 复合语句,逗号运算符 C风格字符串比较、string类字符串比较
- 在win32 api程序中:使用C++风格的字符串
- 字符串的两种不同风格: C++风格和C风格
- C风格类型的字符串在C++中的应用
- 学习C++ -> string类字符串
- C++ 标准头文件与C头文件区别与联系以及C风格字符串
- 在win32 api程序中:使用C++风格的字符串
- C++ vs C 风格的字符串
- C++风格字符串(一)
- C++风格字符串
- C++中string类字符串处理
- C与C++风格字符串
- C 风格字符串[C++]
- C风格字符串[C++]
- C++的字符串: C风格的字符串
- 全面深入介绍C++字符串:string类
- C++中的C风格字符串
- 字符串字面值、C风格字符串、C++风格字符串
- C++字符串存储及string类