1. 程式人生 > >STL-string用法總結

STL-string用法總結

(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類還有關於迭代的函式,這裡不進行講解。