在C++中只有一个字符串类,即basic_string,其管理着一个 '\0' 结尾的字符数组。
头文件:#include <string>
string类支持两种输入方式:cin方式和getline()方式
常见的string类构造函数有以下几种形式:
string s; 空字符串
string s(str); 拷贝字符串str的复制品
string s(str, stridx); 将字符串str中始于stridx的部分,作为字符串 s 的初值
string s(str, strbegin, strlen); 将字符串str中始于stridx的,长度为strlen的部分,作为字符串 s 的初值
string s(Cstr); 以C-string类型 Cstr作为字符串 s 的初值
string s(cstr, char_len); 以C-string类型 Cstr的前char_len个字符串 作为字符串 s 的初值
string s(num, c);
string s(strs, begin, end);
常用string类方法:
empty(); 判断是否为空
+= append() push_back(); 添加字符
= assign(); 赋值
insert(); 插入字符
clear(); 删除所有字符
erase(); 删除字符
resize(); 保留内存以存储一定量的字符
capacity(); 返回字符串容量
replace(); 字符替换
max_size(); 返回字符的最大可能个数
== != < <= => > compare(); 字符串比较
[ ] at(); 获取单一字符
>> getline(); 从stream中读取字符
<< 将值写入stream
copy(); 将内容复制为一个C-string
c_str(); 将内容以C-string形式返回
data(); 将内容以字符数组形式返回
substr(); 返回子字符串
find(); 查找某字符串或数组
int main()
{
string s1;
s1.push_back('j'); // j
s1.push_back('f'); // jf 尾插
s1.push_back('r'); // jfr
// s1.push_back("afg"); //error
s1.pop_back(); // jf 尾删
cout << s1.front() << " " << s1.back() << " "<<s1.at(1)<< " "<<s1[1]<<endl; // j f f f 打印头、尾 值及随机访问
cout << s1.length() << " " << s1.size() << " " << s1.max_size() <<endl; //2 2 2147483647 打印当前字符串长度,及 最大存放长度
cout << s1.capacity()<<" "; //字符容量 15
s1.resize(30); // 改变字符容量
cout << s1.capacity() << endl; // 31
cout << s1.data() << endl; // jf 将内容以字符数组形式返回
string s2 = "hello", s3 = " world",s4;
char arr[] = " everyone";
cout << *arr;
s4.assign(arr); // s4 = everyone 初始化s4
s2.append(s3.append(s4)); // s2 = hello world everyone s3 = world everyone 字符串连接
s3.swap(s2); // s3 = hello world everyone s2 = world everyone 字符串交换
// 原型 size_t copy(char* s, size_t len, size_t pos = 0) const;
s3.copy(arr, 6, 5); // 复制s3中从位置1开始的3个字符到arr中,参数一 是char* 类型
cout << arr << endl; // arr[] = "worldone", world复制过去替换了every
cout << s3.empty()<<endl; // 0 检查s3是否为空
s2.erase(1,5);
cout << s2<<endl; // everyone 删除s2中从1开始的5个字符
s2.erase(s2.begin(), s2.end()); // 删除s2中所有字符
cout << s2.empty() << endl; // 1 s2为空 s2.clear(); 也是一样效果
cout<<s3.compare(s4); // s3大 返回负值 相等返回0 s3小,返回正值
}
// substr()
#include <iostream>
#include <string>
int main ()
{
std::string str="We think in generalities, but we live in details.";
std::string str2 = str.substr (12,12); // str2 = "generalities"
std::string::size_type pos = str.find("live"); // position of "live" in str
std::string str3 = str.substr (pos); // get from "live" to the end
std::cout << str2 << ' ' << str3 << '\n'; // generalities live in details.
return 0;
}
//LeeCode 28 实现strStr()
int strStr(string haystack, string needle)
{
if(needle.size())
return 0;
int pos=haystack.find(needle);
return pos;
}