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;
}