C++筆記 第三十三課 C++中的字串類---狄泰學院
阿新 • • 發佈:2018-11-15
如果在閱讀過程中發現有錯誤,望評論指正,希望大家一起學習,一起進步。
學習C++編譯環境:Linux
第三十三課 C++中的字串類
1.歷史遺留問題
C語言不支援真正意義上的字串
C語言用字元陣列和一組函式實現字串操作
C語言不支援自定義型別,因此無法獲得字串型別
2.解決方案
從C到C++的進化過程引入了自定義型別
在C++中可以通過類完成字串型別的定義
問題:C++中的原生型別系統是否包含字串型別?
3.標準庫中的字串類
C++語言直接支援C語言的所有概念
C++語言中沒有原生的字串型別
C++標準庫提供了string型別
string直接支援字串連線
string直接支援字串的大小比較
string直接支援子串查詢和提取
string直接支援字串的插入和替換
開始使用標準字串類啦~
33-1 字串類的使用—目的:知道字串的基本操作
#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", "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();
33-2 字串和數字的轉換
4.面試題分析
字串迴圈右移
示例:abcdefg迴圈右移3位後得到efgabcd
33-3 用C++完成面試題
#include <iostream>
#include <string>
using namespace std;
string right_func(const string& s, unsigned int n)
{
string ret = "";
unsigned int pos = 0;
// abcdefg==>3 efg abcd
//abc==> 1 cba
//abc==> 3 ==> 1 cba
n = n % s.length();
pos = s.length() - n;
ret = s.substr(pos);
ret += s.substr(0, pos);
//abcdefg ==> 8
//abcdefg ==> 1
//8 % 7 ==> 1
// 7-1==> 6
//abcdef g
// ret ==> g
//ret = g+ abcdef
//ret = gabcdefg
return ret;
}
int main()
{
//string r = right_func("abcdefg", 8);
string r = "abcdefg";
string r = (s>>3);
cout << r << endl;
return 0;
}
執行結果
gabcdef
小結
應用開發中大多數的情況都在進行字串處理
C++中沒有直接支援原生的字串型別
標準庫中通過string類支援字串的概念
string類支援字串和數字的相互轉換
string類的應用使得問題的求解變得簡單