【C++深度剖析學習總結】 33 C++ 中的字符串類

【C++深度剖析學習總結】 33 C++ 中的字符串類

作者 CodeAllen ,轉載請註明出處


1.歷史遺留問題
C語言不支持真正意義上的字符串
C語言用字符數組和一組函數實現字符串操作
C語言不支持自定義類型,因此無法獲得字符串類型

2.解決方案
從C到C++的進化過程引入了自定義類型
在C++中可以通過類完成字符串類型的定義
問題:C++中的原生類型系統是否包含字符串類型? 也是沒有

3.標準庫中的字符串類
C++語言直接支持C語言的所有概念
C++語言中沒有原生的字符串類型
C++標準庫提供了string類型

  • string直接支持字符串連接
  • string直接支持字符串的大小比較
  • string直接支持子串查找和提取
  • string直接支持字符串的插入和替換

實驗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的轉換—支持字符串到數字的轉換
-相關頭文件
istringstream-字符串輸入流
ostringstream-字符串輸出流

使用方法
string->數字
istringstream iss(“123.45”);
double num;
iss >> num;
數字-> string
ostringstream oss;
oss << 543.21;
string s = oss.str();

實驗2 字符串和數字的轉換

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

4.面試題分析
字符串循環右移
示例:abcdefg循環右移3位後得到efgabcd

實驗3 用C++完成面試題 (c++明顯比較好的實現了需求,但是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類的應用使得問題的求解變得簡單

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章