Skip to content

[C++] STL 中的 string 筆記

stringC++ 標準模板函式庫Standard Template Library, STL)中提供的字串容器,跟原本的 char 相比,可以輕鬆做到比較繁瑣的字串操作。

一個最簡單的例子是,原本使用 char 儲存數個字元的陣列,在接受更長長度的字串賦值時,需要先擴充該陣列的長度;然而在使用 string 的情況下,我們可以直接透過 assign() 賦值,而不用去考慮原先儲存字串的變數長度。

那以下就簡單介紹 string 的幾個基本使用方法。由於 string 的操作相當直覺,故應不需要太多的筆記篇幅。

  • 基本操作
  • length()
  • clear()
  • empty()
  • assign()
  • append()
  • find()

string 基本操作

以下來看個 string 簡單的使用方法:

#include <iostream>
#include <string>
using namespace std;


int main() {
    string s = "Today is a nice day.";

    // Print all sentence
    cout << s << endl;

    // Print every character
    for (auto c: s) {
        cout << c << endl;
    }
    
    return 0;
}



Output:

Today is a nice day.
T
o
d
a
y
 
i
s
 
a
 
n
i
c
e
 
d
a
y
.

可以發現,string 型態的變數所儲存的字串,可以直接印出、也可以呼叫每一個字元。當然,除了使用 for-range 的方法印出外,也可以直接指定字串中儲存字符(Character)的編號。

比方說若要呼叫第一個字元 T,則可以使用以下程式碼:

cout << s[0] << endl;



Output:

T

length()

length() 是用來取得字串長度的函式。

#include <iostream>
#include <string>
using namespace std;


int main() {
    string s = "Today is a nice day.";

    // length()
    cout << s.length() << endl;
    
    return 0;
}



Output:

20

clear()

clear() 非常單純,就是將 string 變數直接清空。

#include <iostream>
#include <string>
using namespace std;


int main() {
    string s = "Today is a nice day.";

    // Before
    cout << s << endl;

    // clear()
    s.clear();

    // After
    cout << s << endl;
    
    return 0;
}



Output:

Today is a nice day.

第二行不是我故意留白的 …… 而是因為印出了空字串。可以看到 clear() 函式確實清空了 string 儲存的字串。


empty()

empty() 是用來確認字串是否為空值。若是字串為空,返回 1;若字串不為空,則返回 0。

#include <iostream>
#include <string>
using namespace std;


int main() {
    string s = "Today is a nice day.";

    // Before
    cout << s << s.empty() << endl;

    // clear()
    s.clear();

    // After
    cout << s << s.empty() << endl;
    
    return 0;
}



Output:

Today is a nice day.0
1

assign()

assign() 是用來賦值的函式,基本用法如下:

str_01.assign(str_02, START, NUM)

這是將 str_02 儲存的字串,從編號 START 的字元開始,指定 NUM 個字元賦值給 str_01

#include <iostream>
#include <string>
using namespace std;


int main() {
    string str_01;
    string str_02 = "Today is a nice day.";
    
    // assign()
    str_01.assign(str_02, 6, 100);

    // Print
    cout << str_01 << endl;

    return 0;
}



Output:

is a nice day.

當然,實際上 str_02 並沒有 100 個字元,於是就一口氣 str_02 剩餘的字符都賦值了。


append()

append()assign() 很類似,不過是將 str_02 的字串直接加在 str_01 後頭,同樣可以指定開始點 START 以及字符數量 NUM

#include <iostream>
#include <string>
using namespace std;


int main() {
    string str_01 = "I want to go to play.";
    string str_02 = "Today is a nice day.";
    
    // append()
    str_01 += "\n";
    str_01.append(str_02);

    // Print
    cout << str_01 << endl;

    return 0;
}



Output:

I want to go to play.
Today is a nice day.

可以發現,其實也可以使用 + 來串接字串。


References


Read More

Tags:

Leave a Reply