第五章 - 循环和关系表达式

一,C 风格字符串

1.1,定义C 风格字符串常量

char *str1 = "hello world";
char str2[20] = "hello world";
//定义字符串数组
char *str3[2] = {"hello", "world"};

1.2,对字符串的操作

C语言在string.h(在C++中为cstring)中提供了一些列字符串函数。

1.2.1,strcmp

strcmp函数比较两个字符串的大小,该函数接受两个字符串地址作为参数,这意味着参数可以是指针、字符串常量或字符数组名。如果两个字符串相同,函数返回0;如果第一个字符串大于第二个字符串,函数返回1;如果第一个字符串小于第二个字符串,函数返回-1。

char *str1 = "hello world";
char *str2 = "hold the door";
strcmp(str1, str2);

1.2.2,strcat

把一个字符串连接到已有的一个字符串的后面。

char str1[20] = "hello";
char *str2 = "world";
cout<<strcat(str1, str2);

1.2.3,strcpy

复制一个字符串

char *str1 = "hello";
char str2[10];
strcpy(str2, str1);
cout<<str2<<endl;

1.3,比较C风格的字符串,应注意的问题

要判断字符数组中的字符串是否是”hello”,下面的做法得不到我们想要的结果

char *str = "hello";
str == "hello";

请记住,数组名是数组的地址。同样,用引用括号括起来的字符串常量也是其地址。因此,上面的关系表达式并不是判断两个字符串是否相同,而是查看他们是否存储在相同的位置上。应当使用前面介绍的strcmp()函数来进行比较。

二,C++ string类

2.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;

猜你喜欢

转载自blog.csdn.net/cloud323/article/details/80882022