
一、回顾c语言对字符串的实现: 一般我们在c语言要实现对字符串操作的话,一般是采用字符数组或者一组函数来实现的,为啥这样做呢,那是因为c语言里面根本就没有字符串类型的关键字;而且c语言也支持自定义类型,所以更加无法获得字符串类型 为了解决这个问题,在c++中,引入了自定义类型,而且可以通过类来完成对字符串类型的定义。那么C++中的原生类型系统是否包含字符串类型呢?答案是c++中并没有提供原生的字符串类型。 二、在C++标准库中提供了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 > a[j] ) { swap(a, a[j]); } } } } string string_add(string a[], int len) { string ret = ""; for(int i=0; i<len; i++) { ret += a + "; "; } return ret; } int main() { string sa[7] = { "hello world", "linux", "risc-v", "rust", "c++", "golang", "c" }; string_sort(sa, 7); for(int i=0; i<7; i++) { cout << sa << endl; } cout << endl; cout << string_add(sa, 7) << endl; return 0; } 运行结果: root@txp-virtual-machine:/home/txp/tt# ./a.outc c++ golang hello world linux risc-v rust c;c++;golang;hello world;linux;risc-v;rust; 三、字符串与数字的转换:
相关头文件
1、方法使用 string---数字 istringstream iss("123.45");double num; iss>>num 注:传输成功,表达式值为 true,失败则为 false; 数字---string ostringsream oss;oss << 543.21; string s = oss.str(); 代码示例: #include <iostream>#include <sstream> #include <string> 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(12345); cout << s << endl; return 0; } 输出结果: root@txp-virtual-machine:/home/txp/tt# ./a.out234.567 12345 2、字符串循环右移 比如说"abcdefg"循环右移3位后得到efgabcd 代码示例: #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); //从 pos 开始直到末尾提取子串 ret += s.substr(0, pos);//原来的字符串并没有被破坏,提取到 pos 之前的字符; return ret; } int main() { string s = "abcdefg"; string r = (s >> 3); cout << r << endl; return 0; } 输出结果: root@txp-virtual-machine:/home/txp/tt# ./a.outefgabcd 3、小结:
好了,今天的分享就到这里,如果文章中有错误或者不理解的地方,可以交流互动,一起进步。 |