您的位置:首页 > 编程语言 > C语言/C++

C++ C 风格字符串与string类

2017-04-26 15:48 218 查看
一,C 风格字符串

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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: