c string基礎用法

2021-09-25 19:08:39 字數 1510 閱讀 4158

// string s();  

//生成乙個空字串s

string s1(); // s1 = ""

//string s(str)

//將str字串作為s的初值

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

//string s(num,c);

//生成乙個字串,包含num個c字元

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

//strings(str,stridx,strlen);

//將字串str內「始於stridx且長度頂多strlen」的部分作為字串的初值

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

string s("hello world!");

int slen = s.size(); //slen = 12

int slen2 = s.length(); //slen2 = 12 與size()一樣

// swap() 交換兩個字串的內容

string s1("abcd」), s2("dcba");

s1.swap(s2); // s1 = "dcba",s2 = "abcd"

string s3("abc"), s4("efg");

// insert () 插入字元

string s1("abcd」), s2("666");

s1.insert(2, "123"); //在下標 2 處插入字串"123",s1 = "ab123cd"

s1.insert(3, s2); //在下標 3 處插入 s2 , s1 = "abc666cd"

s1.insert(3, 5, 'x'); //在下標 3 處插入 5 個 'x',s1 = "abc***xxd"

//erase() 刪除字元

string s1("abcd eeee");

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

s1.erase(3); //刪除下標3及其後面的所有字元,此後 s1 = "a e"

// replace() 替換字元

s1.replace(int a, int b, char *s, int n);//刪除從a開始的b個字元,然後在a處插入字串s的前n個字元

s1.replace(int a, int b, string &s);//刪除從a開始的b個字元,然後在a處插入串s

s1.replace(int a, int b, string &s, int pos, int n);//刪除從a開始的b個字元,然後在a處插入串s中從pos開始的n個字元

s1.replace(int a, int b, int n, char c);//刪除從a開始的b個字元,然後在a處插入n個字元c

CString用法集錦

1.cstring compare int compare lpctstr lpsz const 返回值 字串一樣 返回0 小於lpsz 返回 1 大於lpsz 返回1 區分大小字元 cstring s1 abc cstring s2 abd assert s1.compare s2 1 asser...

c string 類基本用法

c 中string是標準庫中一種容器,相當於儲存元素型別為char的vector容器 自己理解 這個類提供了相當豐富的函式來完成對字串操作,以及與c風格字串之間轉換,下面是對string一些總結 引用 一,c語言的字串 在c語言裡,對字串的處理一項都是一件比較痛苦的事情,因為通常在實現字串的操作的時...

c string常用用法

substr函式 string a 01234567 從下標2開始,長度為4,s不變 string b a.substr 2,4 從下標2開始到結束 string c a.substr 2 insert函式 string a 01234567 s會改變 a.insert 2,000 erase函式 ...