C++学习(9)string类

2021-02-26  本文已影响0人  su945

1.string类对象的初始化

– string s1("Hello");
– string month = "March";
– string s2(8,’x’);
可以将字符赋值给string对象

2.string的赋值和连接

• 用 = 赋值
– string s1("cat"), s2;
– s2 = s1;
• 用 assign 成员函数复制
– string s1("cat"), s3;
– s3.assign(s1);
• 用 assign 成员函数部分复制
– string s1("catpig"), s3;
– s3.assign(s1, 1, 3);
– //从s1 中下标为1的字符开始复制3个字符给s3


• 单个字符复制
s2[5] = s1[3] = ‘a’;
• 逐个访问string对象中的字符
string s1("Hello");
for(int i=0;i<s1.length();i++)
cout << s1.at(i) << endl;
• 成员函数at会做范围检查,如果超出范围,会抛出out_of_range异常,而下标运算符[]不做范围检查。


• 用 + 运算符连接字符串
string s1("good "), s2("morning! ");
s1 += s2;
cout << s1;
• 用成员函数 append 连接字符串
string s1("good "), s2("morning! ");
s1.append(s2);
cout << s1;
s2.append(s1, 3, s1.size());//s1.size(), s1字符数
cout << s2;
// 下标为3开始, s1.size()个字符,如果字符串内没有足够字符,则复制到字符串最后一个字符

3.比较string

• 用关系运算符比较string的大小
– == , >, >=, <, <=, !=
– 返回值都是bool类型,成立返回true, 否则返回false
– 例如:

string s1("hello"),s2("hello"),s3("hell");
bool b = (s1 == s2);
cout << b << endl;
b = (s1 == s3);
cout << b << endl;
b = (s1 > s3);
cout << b << endl;
string s1("hello"),s2("hello"),s3("hell");
int f1 = s1.compare(s2);
int f2 = s1.compare(s3);
int f3 = s3.compare(s1);
int f4 = s1.compare(1,2,s3,0,3); //s1 1-2; s3 0-3
int f5 = s1.compare(0,s1.size(),s3);//s1 0-end
cout << f1 << endl << f2 << endl << f3 << endl;
cout << f4 << endl << f5 << endl;

4.查删改

string s1("hello world"), s2;
s2 = s1.substr(4, 5); // 下标4开始5个字符
cout << s2 << endl;

寻找string中的字符
string s1("hello worlld");
cout << s1.find("ll") << endl;
cout << s1.find("abc") << endl;
cout << s1.rfind("ll") << endl;
cout << s1.rfind("abc") << endl;
cout << s1.find_first_of("abcde") << endl;
cout << s1.find_first_of("abc") << endl;
cout << s1.find_last_of("abcde") << endl;
cout << s1.find_last_of("abc") << endl;
cout << s1.find_first_not_of("abcde") << endl;
cout << s1.find_first_not_of("hello world") << endl;
cout << s1.find_last_not_of("abcde") << endl;
cout << s1.find_last_not_of("hello world") << endl;

string input("Input test 123 4.7 A");
istringstream inputString(input);
string string1, string2;
int i;
double d;
char c;
inputString >> string1 >> string2 >> i >> d >> c;
cout << string1 << endl << string2 << endl;
cout << i << endl << d << endl << c << endl;
long L;
if (inputString >> L) cout << "long\n";
else cout << "empty\n";
ostringstream outputString;
int a = 10;
outputString << "This " << a << "ok" << endl;
cout << outputString.str();
上一篇 下一篇

猜你喜欢

热点阅读