-
头文件 。
#include < string > -
string类是一个模板类,位于名字空间std中;
using namespace std;
1. 初始化;
string str; //空字符串
string str1 = "qazwsx";
string str2 = str1;
string str3("qazwsx");
string str4 (5, 'a');
string str5 (str1,2,3); //从str1的第2个位置的字符开始,连续3个字符赋值给s5,即s5="zws";
string str6(str1,2); //从str1的2位置的字符开始,将后续的所有字符赋值给str6,即s6="zwsx";
string str;
cin>>str; //当使用C++的cin读入字符串时,程序遇到空白字符就停止读取了。
//若输入为“ hello world” ,则 str == "hello";
//如果我们想读取一整行输入,包括空格及空格后面的字符,我们可以使用getline。
string str;
getline(cin, str);
cout << str << endl; //若输入同样为“hello world”,则str =="hello world";
2.string特性描述
//find, 查找字符串A是否包含子串B
if( strA.find(strB) != string:npos)
.......//找到了
else
.......//没找到
str.size() ; //返回字符串有效字符长度
str.length(); //返回字符串有效的长度
str.capacity() ; //返回空间总大小,既容量
str.empty() ; //判断字符串是否为空串,是返回true,不是返回false
void clear(); //清空有效的字符
3.迭代器iterator
string::iterator it;
for (it = s1.begin(); it != s1.end(); it++){
cout << *it << endl;
}
#include<iostream>
#include<string>
#include <algorithm>
using namespace std;
int main(){
//初始化
string a = "apple";
string aa("banana");
cout << "a = " << a << "; sizeof a = "<<a.size()<<endl;
cout << "aa = " << aa << "; sizeof aa = " << aa.size() << endl;
//字符串扩展
string aaa = a + " " + aa;
cout << "aaa= " << aaa<< "; sizeof aaa = " << aaa.size() << endl;
aaa.append(" orange");
cout << "aaa= " << aaa << "; sizeof aaa = " << aaa.size() << endl;
//find()
if (aaa.find("banana") != string::npos) {
cout << "there is a banana in aaa"<<endl;
}
//迭代器
string::iterator it;
for (it = a.begin(); it != a.end(); ++it) {
cout << *it ;
}
cout << endl;
//大小写转化
//使用迭代器+toupper
for (it = a.begin(); it != a.end(); ++it) {
char upper = toupper(*it);
cout << upper;
}
cout << endl;
//使用transform+toupper(需包含头文件 algorithm)
transform(a.begin(), a.end(), a.begin(), toupper);
cout << "transform+toupper: "<<a << endl;
//string 和 char[ ],char * 相互转换
const char* change ="i need to change char* to string";
string change_to_string = change;
cout << change_to_string << endl;
system("pause");
return 0;
}