3-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(int argc, const char *argv[]) {
string sa[7] = {
"Hello World",
"D.T.Software",
"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的转换
<sstream>--相关头文件
istringstream--字符串输入流
ostringstream--字符串输出流
使用方法:
- 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(int argc, const char *argv[]) {
double n = 0;
if (TO_NUMBER("234.567", n)) {
cout << n << endl;
}
string s = TO_STRING(12345);
cout << s << endl;
return 0;
}
面试题分析
字符串循环右移:
例如:agcdefg循环右移3位后得到efgabcd
【范例代码】字符串循环右移3位
#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(int argc, const char *argv[]) {
string s = "abcdefg";
string r = (s >> 3);
cout << r << endl;
return 0;
}