STL - string用法總結

(我的STL相關的博客目錄:https://blog.csdn.net/Kprogram/article/details/90408011

(string-c++官網:http://www.cplusplus.com/reference/string/string/?kw=string

stirng有什麼使用價值呢?

字符數組是C中非常常用而又麻煩的一個東西:

    如果分配的初始空間不夠,會造成字符丟失和數組越界;

    如果沒有很好的初始化(如初始化爲'\0'),也可能會造成數組越界,打印時可能還會顯示奇怪的字符;

    即使做好了各種細節工作,對其的變換和比較等操作也是很麻煩。

於是C++提供了string類:

   長度不定,且擁有很多實用的成員函數,能在很多地方完美地替代字符數組,是一個非常便捷的東西。

    它能方便的和字符數組互相轉換:string 可以直接就被賦值於字符數組(char a[10]; string s = a),而copy函數可以把string中的字符複製到字符數組中(末尾有使用詳解)

接下來我來講解string的使用方法:

0 - 頭文件:string  命名空間:std

#include <string>
using namespace std;

1 - 聲明一個string,併爲其賦值

    string 有多種賦值方法:

1.不賦值:
string s0;
2.初始化時賦值:
string s1 = "deep";
string s2("dark");
string s4(10, "fantacy");
string s3 = s2; //拷貝
3.用字符數組賦值:
char sz[100];
scanf("%s", sz);
string s5 = sz;
4.用cin賦值:
string s6;
cin >> s6;

2 - 便捷的成員函數 ( 假設你創建的string對象名字叫 S )

    (色爲重要函數,色爲常用函數,帶* 的爲很少使用的函數,大部分情況下紅+粉紅函數就夠用了)

容量和尺寸

    size():返回字符串的尺寸,因爲是以byte爲單位的,所以可能不是字符的實際數量(但ASCALL字符串的尺寸一定是其長度)

        length():跟size作用一毛一樣(官網上說的哈,我也實驗過了)

        maxsize():返回字符串的最大尺寸,沒啥用(雖然string長度可變,但爲了省時,它會預分配一些多的空間,所以maxsize >= size)

    empy():如果字符串爲空,返回True, 反之則返回 False。

    clear():變爲空串。

    resize(n):重新設置字符串的長度,如果n小於size,則保留前n個字符。反之,隨便增加字符到n,或者增加指定字符:S.resize(n, 'c')

    *capacity():返回string的容量大小,容量不同於size,如果元素的數量超過了容量string會重新分配內存,以存儲更多的元素,而且會造成一些影響。

    *reserve(n):重置string的容量,如果n小於容量,則不會造成影響,這個函數也沒啥用。

    *shrink_to_fit():縮小容量至其等於size。

元素

    S[n]:跟數組一個道理

    back():返回最後一個元素的引用(意味着可以用V.back() = data修改末尾元素值)

    front():返回第一個元素的引用

    at(n):返回第n個元素的引用

修改操作

    insert():插入字符串

string str="to be question";
string str2="the ";
string str3="or not to be";
               //插入方法和插入之後的結果
//插入於第六個字符處
str.insert(6,str2);                 // to be (the )question
//把str3的第3個字符向後數4個字符插入
str.insert(6,str3,3,4);             // to be (not )the question
//插入8個字符
str.insert(10,"that is cool",8);    // to be not (that is )the question
str.insert(10,"to be ");            // to be not (to be )that is the question
str.insert(15,3,':');               // to be not to be(:::) that is the question

    erase(n):刪除第n個字符

        erase(a, b):刪除[a, b]內所有字符

    replace():替換字符串

string base="this is a test string.";
string str2="n example";
string str3="sample phrase";
string str4="useful.";

string str=base;           // "this is a test string."
//從str的第9個往後數5個的字符串被替換
str.replace(9,5,str2);          // "this is an example string." (1)
//同理,把str3的第7個後數6個字符用來替換
str.replace(19,6,str3,7,6);     // "this is an example phrase." (2)
str.replace(8,10,"just a");     // "this is just a phrase."     (3)
str.replace(8,6,"a shorty",7);  // "this is a short phrase."    (4)
//重複三次
str.replace(22,1,3,'!');        // "this is a short phrase!!!"  (5)

    operator+=在字符串後面添加字符串。

        append(string):同上,括號內可以是string對象,也可以是一串字符。

        operator+:可以把兩個字符串相加

string S = "123";
S += "456"; 或 S.append("456")
cout << S << endl;
//output:
123456

    push_back(char):添加一個字符到向量的末尾

        pop_back()刪除末尾字符

    S.swap(S1):交換 S 和 S1 兩個string

    *assign():不太用的上,實在想了解點這裏>useless<

字符串操作:(有匹配子串,比較等重要函數)

    compare(str):比較兩個字符串,相同返回1,不同返回0。參數的設置和replace原理相同!

string str1 ("green apple");
string str2 ("red apple");

1.比較整個字符串
str1.compare(str2)

2.比較第6個字符開始到往後數5個字符(apple)
str1.compare(6,5,"apple")

3.把str2的第4個字符開始到往後數5個字符(也是apple)用來比較
str1.compare(6,5,str2,4,5)

    find():在字符串中尋找給定的字符串,返回的是找到的第一個匹配子串首位置,若沒找到,返回string::npos(其實是一個無符號整形)

        rfind():同find相反,返回的是最後一個匹配子串的位置。

1.從頭尋找
unsigned int found = str.find(str2);
if (found!=string::npos)
  cout << "first 'needle' found at: " << found << '\n';

2.從第n個字符處開始尋找
found=str.find("needles are small",found+1,6);
if (found!=string::npos)
  cout << "second 'needle' found at: " << found << '\n';

可以用此方法替換掉第一個needles
str.replace(str.find(str2),str2.length(),"preposition");

    substr():裁剪字符串,返回裁剪下來的內容。對被裁剪的字符串不產生影響。

        substr(a, b)裁剪下a - b的字符; substr(n)裁剪下n之後的字符

    copy():與substr不同,它是用把string上的字符拷貝到char[]裏。(注意,參數的順序跟上面那些函數有點不同)

char buffer[20];
string str ("Test string...");
從第5個字符開始,拷貝6個字符到buffer中
size_t length = str.copy(buffer,6,5);
buffer[length] = '\0';
scout << "buffer contains: " << buffer << '\n';
//out put:
string

    find_first_of(str):在字符串中搜索與參數中指定的任何字符匹配的第一個字符。(比如str = "123",它就返回1,2 或者 3這三個字符之一在字符串裏面最先出現的地方,例:"a2aa",返回1;"abc321ad" 返回3)

        find_last_of(str):同理,不過是從後面開始找

        find_first_not_of(str);這時候是找不在str裏面的字符的第一個位置了

        find_last_not_of(str):同理

 

string類還有關於迭代的函數,這裏不進行講解。

    

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