1.引言 1.1什么是字符串 字符串是由一系列字符组成的序列。用于表示文本信息。被广泛用于用户交互,文件处理,数据解析场景中
1.2C/C++ 风格 在C++中,由两种主要的字符串类型:
·C风格字符串 :基于字符数组,以空字符(‘\0’)结尾
·C++ std::string类 :更高级,功能更丰富,封装了字符串操作的复杂性。
C风格字符串示例 :
1 char cstr[] = "hello,world" ;
C++ std::string示例 :
1 2 #include <string> std::string str = "hello,world" ;
2.std::string 基础 2.1定义与初始化 1 2 3 4 5 6 7 8 9 10 11 #include <string> std::string str; std::string str2 = "hello" ; std::string str3 (str2) ; std::string str4 (str2, 0 , 4 ) ;std::string str5 (5 , 'a' ) ;
2.2字符串的输入输出 string类中已经帮我们重载了输入输出函数,直接输入输出就好
1 2 3 std::string str; std::cin >> str; std::cout << str << endl;
3.字符串操作 3.1 拼接与连接
getline(is, s) 从 is中读取一行赋值給s,返回 is
s.empty() s为空返回true,否则返回false
s.size() 返回s中的字符个数
s[n] 返回s中第n个字符的引用,位置n从0记起
s1 + s2 返回s1和 s2 连接后的结果
s1 = s2 用s2 的副本代替s1 中原来的字符
s1 == s2 如果s1 和s2 中所含字符完全一样,则它们相等
s1 != s2 等性判断对字母的大小写敏感
<, <=, >, >= 利用字符在字典中的顺序进行比较,且对字母大小写敏感
3.2 查找和替换 使用find()查找
1 2 3 4 5 std::string str = "aaaabbbbcccc" ; std::string word = "aab" ; size_t pos = str.find (word);
替换
1 2 3 4 5 6 7 std::string text = "i like cats" ; std::string from = "cats" ; std::string to = "dogs" ; std::string pos = text.find (from); text.replace (pos, from.length (), to);
截取
1 2 3 4 5 std::string str = "hello world!" ; std::string sub = str.substr (7 , 5 ); std::cout << sub << endl;
其他有用的函数
empty():检查字符串是否为空
clear():清空该字符串内容
erase():删除字符串部分内容
insert():在指定位置插入字符串
replace():替换字符串部分内容
4.高级用法 4.1 字符串流(stringstream) std::stringstream是C++标准库中<sstream>头文件提供的一个类,用于在内存中进行字符串的读写操作,类似于文件流。
基本用法示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 #include <iostream> #include <sstream> #include <string> int main () { std::stringstream ss; ss << "value: " << 42 << ", " << 3.14 ; std::string result = ss.str (); std::cout << result << std::endl; return 0 ; }
从字符串流中读取数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #include <iostream> #include <sstream> #include <string> int main () { std::string data = "123 45.67 hello" ; std::stringstream ss (data) ; int a; double b; std::string c; ss >> a >> b >> c; std::cout << "a: " << a << ",b: " << b << ",c: " << c << std::endl; return 0 ; }
4.2 字符串与其他类型的转换 将其他类型转化为std::string
·使用std::to_string() :
1 2 3 4 5 6 7 int num = 100 ;double pi = 3.1415 ;std::string str1 = std::to_string (num); std::string str2 = std::to_string (pi);
将std::string转换为其他类型
·使用字符串流:
1 2 3 4 5 6 7 8 9 10 11 12 std::string numstr = "234" ; std::string pistr = "3.14" ; int num;double pi;std::stringstream ss1 (numstr) ;ss1 >> num; std::stringstream ss2 (pistr) ;ss2 >> pi;
·使用std::stoi(),std::stod等函数(C++11 及以上)
1 2 3 4 5 std::string numstr = "123" ; std::string pistr = "3.14" ; int num = std::stoi (numstr); double pi = std::stod (pistr);