String函式使用筆記

2022-08-25 15:42:18 字數 1606 閱讀 7979

以下是學習字串時學習的筆記,僅供參考

大部分內容來自c語言學習網,我只是以我的理解來解釋,而且後面全偷懶了

目錄字串的比較

求子串交換兩個字串

查詢子串和字元

刪除子串

string s1();  // si = ""

string s2("hello"); // s2 = "hello"

string s3(4, 'k'); // s3 = "kkkk"

string s4("12345", 1, 3); //s4 = "234",即 "12345" 的從下標 1 開始,長度為 3 的子串

s1.size();

s1.length();

兩者無任何區別

勿將其與strlen()混淆!

有兩種做法

string s1("123"),s2("abc")
string s1("123"),s2("abc")

s1=s1+s2;//s1="123abc"

同樣有兩種做法

這個不解釋了

string s1("hello"), s2("hello, world");

int n = s1.compare(s2);

n = s1.compare(1, 2, s2, 0, 3); //比較s1的子串 (1,2) 和s2的子串 (0,3)

n = s1.compare(0, 2, s2); // 比較s1的子串 (0,2) 和 s2

n = s1.compare("hello");

n = s1.compare(1, 2, "hello"); //比較 s1 的子串(1,2)和"hello」

n = s1.compare(1, 2, "hello", 1, 2); //比較 s1 在位置1到2的字串和 "hello" 在位置1至2的子串

string s1 = "this is ok";

string s2 = s1.substr(2, 4); // s2 = "is i"

s2 = s1.substr(2); // s2 = "is is ok"

s1.swap(s2);
string 類有一些查詢子串和字元的成員函式,它們的返回值都是子串或字元在 string 物件字串中的位置(即下標)。如果查不到,則返回 string::npos。string: :npos 是在 string 類中定義的乙個靜態常量。這些函式如下:

下面是 string 類的查詢成員函式的示例程式。

#include #include using namespace std;

int main()

string s1("real steel");

s1.erase(1, 3); //刪除子串(1, 3),此後 s1 = "r steel"

s1.erase(5); //刪除位置在5及其後面的所有字元,此後 s1 = "r ste"

linux C getchar函式使用 筆記

1 函式原型 int getchar void 2 函式功能 從stdin中讀取乙個字元。3 返回值 返回讀取字元的ascii值或者eof字元或者出錯值。4 標頭檔案 include linux下編寫的乙個例子 include int main void printf nthe string len...

Vim 使用筆記

set hlsearch set nohlsearch 搜尋後清除上次的加亮 nohl nohlsearch 拷貝 很有用的一句話,規定了格式選項,讓它換行不自動空格 set formatoptions tcrqn set fo r set noautoindent 再 shift insert 正...

xemacs使用筆記

xemacs使用筆記 xemacs emacs的下一代,由lucid原創 from debian參考手冊.由於不知道什麼時候刪掉了emacs的乙個重要檔案.每次都沒法安裝好.突然發現了xemacs,於是決定使用看看.本人還是菜鳥,僅供交流 我使用的ubuntu系統,所以就直接apt get inst...