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[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",
"AutumnZe",
"C#",
"Java",
"C++",
"Python",
"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;
}
输出结果如下:
字符串与数字的转换
标准库中提供了相关的类对字符串和数字进行转换
字符串流类 ( sstream ) 用于 string 的转换
使用方法:
string --> 数字
istringstream iss("123.45");
double num;
iss > > num;
数字 --> string
ostringstream 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;
}
输出结果如下:
C++ 中还可以通过模板技术进行字符串和数字转换,这里先用宏来实现。
示例 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);
ret += s.substr(0, pos);
return ret;
}
int main()
{
string s = "abcdefg";
string r = (s >> 8);
cout << r << endl;
return 0;
}
输出结果如下:
分析过程如下:
abcdefg ==> 8 等价于 abcdefg ==> 1 (因为 8 % 7 = 1)
7 - 1 =6
所以把 g 提出来
ret = g
然后 ret = g + abcdef
就是最终结果 gabcdef