第33课 C++中的字符串类

在C语言中学习字符串时,我们使用的是字符数组的概念。

C语言中没有真正意义的字符串。为了表达字符串的概念,我们使用了字符数组来模拟字符串。

在应用程序开发中,我们需要大量的处理字符串,如果还用C语言中的方式,效率就显得太低了。

 C++中也没有原生的字符串数据类型,C++中为了兼容C,也不支持字符串类型,也是用字符数组和一组函数的方式来实现字符串的操作。

不一样的是C++中支持自定义类型。

解决方案:

C++原生系统类型不支持字符串。我们完全可以用自定义类型来实现一个字符串。

标准库中的字符串类:

字符串类的使用:

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 void string_sort(string a[], int len)
 7 {
 8     for(int i=0; i<len; i++)
 9     {
10         for(int j=i; j<len; j++)
11         {
12             if( a[i] > a[j] )
13             {
14                 swap(a[i], a[j]);
15             }
16         }
17     }
18 }
19 
20 string string_add(string a[], int len)
21 {
22     string ret = "";
23     
24     for(int i=0; i<len; i++)
25     {
26         ret += a[i] + "; ";
27     }
28     
29     return ret;
30 }
31 
32 int main()
33 {
34     string sa[7] = 
35     {
36         "Hello World",
37         "D.T.Software",
38         "C#",
39         "Java",
40         "C++",
41         "Python",
42         "TypeScript"
43     };
44     
45     string_sort(sa, 7);
46     
47     for(int i=0; i<7; i++)
48     {
49         cout << sa[i] << endl;
50     }
51     
52     cout << endl;
53     
54     cout << string_add(sa, 7) << endl;
55     
56     return 0;
57 }

运行结果如下:

这个程序我们是使用字符串类来完成的,用到了两个字符串类的大小比较和字符串类的相加。

在C++中我们没有必要在使用字符数组来表示字符串了,直接使用标准库中的string类型即可。

字符串与数字的转换:

sstream类的诞生就是为了支持字符串到类的转换。

使用方法:

实验程序:

结果如下:

第12行的程序是有返回值的,改进如下:

abcdefg转换不会成功,因此,14行不会执行,如下:

 18行还可以写成如下的形式:

 工程中我们还要再进行一次封装:

 1 #include <iostream>
 2 #include <sstream>
 3 #include <string>
 4 
 5 using namespace std;
 6 
 7 
 8 #define TO_NUMBER(s, n) (istringstream(s) >> n)
 9 #define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str())
10 
11 int main()
12 {
13 
14     double n = 0;
15    
16     if( TO_NUMBER("234.567", n) )
17     {
18         cout << n << endl;    
19     }
20 
21     string s = TO_STRING(12345);
22 
23     cout << s << endl;     
24     
25     return 0;
26 }

 运行结果如下:

 面试题分析:

程序与结果:

既然是C++,我们通过重载右移操作符的方式再实现一次,如下:

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 string operator >> (const string& s, unsigned int n)
 7 {
 8     string ret = "";
 9     unsigned int pos = 0;
10     
11     n = n % s.length();
12     pos = s.length() - n;
13     ret = s.substr(pos);
14     ret += s.substr(0, pos);
15     
16     return ret;
17 }
18 
19 int main()
20 {
21     string s = "abcdefg";
22     string r = (s >> 3);
23     
24     cout << r << endl;
25     
26     return 0;
27 }

 运行结果和上面一样。

 字符串反转:

小结:

原文地址:https://www.cnblogs.com/wanmeishenghuo/p/9571833.html