- 要使用 string 类,必须包含头文件
<string>
- 实质**\0** 结尾的字符数组
- 定义与输入
string s;
cin >> s;
- string的函数和用法
- 构造函数
string strs //生成空字符串
string s(str) //生成字符串str的复制品
string s(str, stridx) //将字符串str中始于stridx的部分作为构造函数的初值
string s(str, strbegin, strlen) //将字符串str中始于strbegin、长度为strlen的部分作为字符串初值
strings(num, c) //生成一个字符串,包含num个c字符
strings(strs, beg, end) //以区间[beg, end]内的字符作为字符串s的初值
- 析构函数(基本不用)~string() //销毁所有内存,释放内存
- 有关大小和容量的成员函数
string s("abcdefg");
cout<<s.size()<<s.length();
结果都为7
- 赋值
string s1("abcdefg");
string s2;
s2.assign(s1);
s2 = s1; //与上等同作用
- 交换两个字符串
string s1("abcdefg");
string s2("1234567");
swap(s1,s2);
string s3;
s3 = s1;
s1 = s2;
s2 = s3;
两种方法
- 添加字符(串)
string s1("abcdefg");
string s2("1234567");
s1 = s1+s2;
cout<<s1<<endl;
s1 = s1+"hhhh";
cout<<s1<<endl;
s1.append("sdf");
cout<<s1<<endl;
abcdefg1234567
abcdefg1234567hhhh
abcdefg1234567hhhhsdf
replace()
basic_string& replace( size_type pos, size_type count,
const basic_string& str,
size_type pos2, size_type count2 = npos );
basic_string& replace( size_type pos, size_type count,
size_type count2, CharT ch );
basic_string& replace( const_iterator first, const_iterator last,
size_type count2, CharT ch );
basic_string& replace( const_iterator first, const_iterator last,
const basic_string& str );
basic_string& replace( size_type pos, size_type count,
const basic_string& str,
size_type pos2, size_type count2 );
参数
pos 将被替换的子串起始位置
count 将被替换的子串长度
first, last 将被替换的字符范围
str 用于替换的 string
pos2 用于替换的子串起始位置
count2 用于替换的字符数
ch 用于替换的字符值
first2, last2 用于替换的字符范围
- empty ()判断字符串是否为空
- ==,! =,<,<=,>,>=,compare() 比较字符串内容
- find()
搜寻某子字符串或字符
str.find(str2)
当str2是str的字串时,返回其在str中第一次出现的位置;
如果str2不是str的字串,返回string::npos (-1);
附:(c++所有成员函数)
其中substr中两个参数分别是第一个字符的位置,第二个参数是要字符的长度
以空格分隔字符串的方法
class Solution {
public:
int isPrefixOfWord(string sentence, string searchWord) {
istringstream ss(sentence);
string str;
for (int i = 1; ss >> str; i ++)
if (str.find(searchWord) == 0) return i;
return -1;
}
};