历史遗留问题C 语言不支持真正意义上的字符串C 语言用字符数组和一组函数实现字符串操作C 语言不支持自定义类型,因此无法获得字符串类型解决方案从 C 到 C++ 的进化过程中引入了自定义类型在 C++ 中可以通过类完成字符串类型的定义问题:C++ 中原生类型系统是否包含字符串类型呢?标准库中的字符串类C++ 语言支持 C 语言的所有概念C++ 语言中没有原生的字符串类型C++ 标准库提供给了 string 类型string 直接支持字符串连接string 直接支持字符串的大小比较string 直接支持子串查找和提取string 直接支持字符串的插入和替换编程实验: 字符串类的使用#include <iostream>#include <string>using namespace std;void string_sort(string a[], int len){ for(int i=0; i<len; i++) { for(int j=i; j<len; j++) { if(a[i] > a[j]) { swap(a[i], a[j]); } } }}string string_add(string a[], int len){ string ret = “”; for(int i=0; i<len; i++) { ret += a[i] + “; “; } return ret;}int main(){ string sa[7] = { “Hello World”, “D.T.Software”, “C#”, “Java”, “C++”, “Phthon”, “TypeScript” }; string_sort(sa, 7); for(int i=0; i<7; i++) { cout << sa[i] << endl; } cout << endl; cout << string_add(sa, 7) << endl; return 0;}输出:C#C++D.T.SoftwareHello WorldJavaPhthonTypeScriptC#; C++; D.T.Software; Hello World; Java; Phthon; TypeScript; 字符串与数字的转换标准库中提供了相关的类对字符串和数字进行转换字符串流 ( sstream ) 用于 string 的转换<sstream> - 相关头文件istringstream - 字符串输入流ostringstream - 字符串输出流使用方法:string –> 数字void code_1(){ istringstream iss(“123.45”); double num; iss >> num;}数字 –> stringvoid code_2(){ ostringstream oss; oss << 543.21; string s = oss.str();}编程实验: 字符串和数字的转换test_1.cpp#include <iostream>#include <string>#include <sstream>using namespace std;int main(){ // ——– istringstream iss(“123.567”); double num = 0; if( iss >> num ) // 注意这里! { cout << num << endl; } // ——- ostringstream oss; oss << 765 << “.” << 321; // 注意这里! string s = oss.str(); cout << s << endl; return 0;}输出:123.567765.321总结:ostringstream 对象 << :返回输出流对象本身istringstream 对象 >> :返回转换结果 (成功 true, 失败 false)工程中的用法: test_2.cpp#include <iostream>#include <string>#include <sstream>using namespace std;#define TO_NUMBER(s, n) (istringstream(s) >> n)#define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str())int main(){ double n = 0; if( TO_NUMBER(“234.567”, n) ) { cout << n << endl; } string s = TO_STRING(765.432); cout << s << endl; return 0;}输出:234.567765.432面试分析字符串循环右移示例: abcdefg 循环右移 3 位后得到 efgadcd编程实验: 使用 C++ 完成面试题#include <iostream>#include <string>using namespace std;string operator << (const string& s, unsigned int n){ string ret = “”; unsigned int pos = 0; n = n % s.length(); pos = s.length() - n; ret = s.substr(pos); ret += s.substr(0, pos); return ret;}int main(){ string s = “abcdefg”; string r = s << 3; cout << r << endl; return 0;}输出:efgabcd小结应用开发中大多数的情况都在进行字符串处理C++ 中没有直接支持原生的字符串类型标准库中通过 string 类支持字符串的概念string 类支持字符串和数字的相互转换string 类的应用使得问题的求解变得简单以上内容参考狄泰软件学院系列课程,请大家保护原创!