1、C++语言中, 字符串有三种形式:
(1)用双引号括起来的字符串常量。
一个字符串占据内存的字节数等于字符串中字符数目加1 ('\0')
提到字符串的长度时, 是不将结尾的'\0'计算在内的
细节提醒:字符'\0'的ASCII码就是0
'\'字符在字符串中出现时,变成'\\'
(2)存放于字符数组中的字符串
字符数组的元素个数,应该不少于被存储的字符数目加1(数组中需包含一个'\0'字符,代表字符串的结尾)
如果被存储的字符数目大于“字符数组的元素个数加1” ,将会发生数组越界的错误。
cin将字符串读入字符数组时,cin会自动在字符数组中字符串的末尾加上'\0'
细节提醒:用cin输入字符串时, 输入的字符串中不能有空格,否则被读入的就是空格前面的部分。
(如果想要将用户输入的包含一个甚至多个空格的一整行都当做一个字符串读入到prisonName(一个字符 数组)中,则可使用如cin.getline(prisonName, 99)
getline函数原型为getline(char buf[ ], int bufSize)
(3)string对象
与字符数组不同的是string对象的体积, 大小是固定的,即表达式sizeof(string) 的值是固定的,和其中存放的字符串的长度无关。这个固定的值在不同的编译器上是不同的。(例如,Dev C++中是4,在Visual studio 2010中是32)
string 对象不会直接存放字符串,字符串会在别处开辟内存空间存放,string对象中只存放该内存空间的地址或其他一些信息。
string对象的赋值:
string对象之间可以互相赋值,也可以用字符串常量和字符数组的名字对string 对象进行赋值,赋值时不需要考虑被赋值的对 象是否有足够空间存放字符串的问题。
string对象的运算:
string对象之间可以用"<"、"<="、"=="、">="、">"运算符进行比较,还可以用"+"运算符将string对象相加,或将一个字符串常 量和string对象相加,或将一个字符数组和string对象相加(相当于字符串连接),"+="运算符也适用于string对象,此外, string对象还可以通过"[ ]" 运算符和下标,存取字符串的某个字符。
细节提醒:string对象比较大小时,是按词典顺序比较,而且是大小写相关的。大写字母的ASCII码小于小写字母的 ASCII 码('A'~'Z'的ASCII码是0x41 ~0x5a, 'a'~'z'的ASCII码是0x61~0x7a)
<以上内容引自 郭玮 《新版C++程序设计教程》>
附代码:
6.2.1 字符数组:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char title[] = "Prison Break";
char hero[100] = "Michael Scofield";
char prisonName[100];
char response[100];
cout << "What's the name of the prison in" << title << endl;
cin >> prisonName;
if(strcmp(prisonName, "Fox-River") == 0)
cout << "Yeah, Do you love" << hero << endl;
else{
strcpy(response, "It seems you haven't watched it!\n");
cout << response;
}
title[0] = 't';
title[3] = 0;
cout << title << endl;
return 0;
}
6.3字符串函数
#include <iostream>
#include <cstring>
using namespace std;
void PrintSmall(char s1[], char s2[]){
if(strcmp(s1, s2) <= 0)
cout << s1;
else
cout << s2;
}
int main(){
char s1[20];
char s2[40];
char s3[100];
strcpy(s1, "Hello");
strcpy(s2, s1);
cout << "1)" << s2 << endl;
strcat(s1, ", world");
cout << "2)" << s1 << endl;
cout << "3)"; PrintSmall("abc", s2); cout << endl;
cout << "4)"; PrintSmall("abc", "aaa"); cout << endl;
int n = strlen(s2);
cout << "5)" << n << ", " << strlen("abc") << endl;
strupr(s1);
cout << "6)" << s1 << endl;
return 0;
}
6.4.5 string对象用法示例
#include <cstring>
#include <iostream>
using namespace std;
int main(){
string s1 = "123", s2;
s2 += s1;
s1 = "abc";
s1 += "def";
cout << "1)" << s1 << endl;
if(s2 < s1)
cout << "2)s2 < s1" <<endl;
else
cout << "2)s2 >= s1" << endl;
s2[1] = 'A';
s1 = "XYZ" + s2;
string s3 = s1 + s2;
cout << "3)" << s3 << endl;
cout << "4)" << s3.size() <<endl;
string s4 = s3.substr(1,3);
char str[20];
strcpy(str, s4.c_str());
cout <<"6) " << str << endl;
return 0;
}