當前位置

首頁 > 商務英語 > 計算機英語 > c中string的用法

c中string的用法

推薦人: 來源: 閱讀: 1.81W 次

c中string的用法的用法你知道嗎?下面小編就跟你們詳細介紹下c中string的用法的用法,希望對你們有用。

c中string的用法

  c中string的用法的用法如下:

為了在我們的程式中使用string型別,我們必須包含標頭檔案 <string>。

如下:

#include <string> //注意這裡不是string.h string.h是C字串標頭檔案

#include <string>

using namespace std;

1.宣告一個C++字串

宣告一個字串變數很簡單:

string Str;

這樣我們就聲明瞭一個字串變數,但既然是一個類,就有建構函式和解構函式。上面的宣告沒有傳入引數,所以就直接使用了string的預設的建構函式,這個函式所作的就是把Str初始化為一個空字串。String類的建構函式和解構函式如下:

a) string s; //生成一個空字串s

b) string s(str) //拷貝建構函式 生成str的複製品

c) string s(str,stridx) //將字串str內“始於位置stridx”的部分當作字串的初值

d) string s(str,stridx,strlen) //將字串str內“始於stridx且長度頂多strlen”的部分作為字串的初值

e) string s(cstr) //將C字串作為s的初值

f) string s(chars,chars_len) //將C字串前chars_len個字元作為字串s的初值。

g) string s(num,c) //生成一個字串,包含num個c字元

h) string s(beg,end) //以區間beg;end(不包含end)內的字元作為字串s的初值

i) s.~string() //銷燬所有字元,釋放記憶體

都很簡單,我就不解釋了。

2.字串操作函式

這裡是C++字串的重點,我先把各種操作函式羅列出來,不喜歡把所有函式都看完的人可以在這裡找自己喜歡的函式,再到後面看他的詳細解釋。

a) =,assign() //賦以新值

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

c) +=,append(),push_back() //在尾部新增字元

d) insert() //插入字元

e) erase() //刪除字元

f) clear() //刪除全部字元

g) replace() //替換字元

h) + //串聯字串

i) ==,!=,<,<=,>,>=,compare() //比較字串

j) size(),length() //返回字元數量

k) max_size() //返回字元的可能最大個數

l) empty() //判斷字串是否為空

m) capacity() //返回重新分配之前的字元容量

n) reserve() //保留一定量記憶體以容納一定數量的字元

o) [ ], at() //存取單一字元

p) >>,getline() //從stream讀取某值

q) << //將謀值寫入stream

r) copy() //將某值賦值為一個C_string

s) c_str() //將內容以C_string返回

t) data() //將內容以字元陣列形式返回

u) substr() //返回某個子字串

v)查詢函式

w)begin() end() //提供類似STL的迭代器支援

x) rbegin() rend() //逆向迭代器

y) get_allocator() //返回配置器

下面詳細介紹:

2.1 C++字串和C字串的轉換

C ++提供的由C++字串得到對應的C_string的方法是使用data()、c_str()和copy(),其中,data()以字元陣列的形式返回字串內容,但並不新增'/0'。c_str()返回一個以‘/0'結尾的字元陣列,而copy()則把字串的內容複製或寫入既有的c_string或 字元陣列內。C++字串並不以'/0'結尾。我的建議是在程式中能使用C++字串就使用,除非萬不得已不選用c_string。由於只是簡單介紹,詳細介紹掠過,誰想進一步瞭解使用中的注意事項可以給我留言(到我的收件箱)。我詳細解釋。

2.2 大小和容量函式

一個C++字串存在三種大小:a)現有的字元數,函式是size()和length(),他們等效。Empty()用來檢查字串是否為空。b)max_size() 這個大小是指當前C++字串最多能包含的字元數,很可能和機器本身的限制或者字串所在位置連續記憶體的大小有關係。我們一般情況下不用關心他,應該大小足夠我們用的。但是不夠用的話,會丟擲length_error異常c)capacity()重新分配記憶體之前 string所能包含的最大字元數。這裡另一個需要指出的是reserve()函式,這個函式為string重新分配記憶體。重新分配的大小由其引數決定, 預設引數為0,這時候會對string進行非強制性縮減。

還有必要再重複一下C++字串和C字串轉換的問 題,許多人會遇到這樣的問題,自己做的程式要呼叫別人的函式、類什麼的(比如資料庫連線函式Connect(char*,char*)),但別人的函式參 數用的是char*形式的,而我們知道,c_str()、data()返回的字元陣列由該字串擁有,所以是一種const char*,要想作為上面提及的函式的引數,還必須拷貝到一個char*,而我們的原則是能不使用C字串就不使用。那麼,這時候我們的處理方式是:如果 此函式對引數(也就是char*)的內容不修改的話,我們可以這樣Connect((char*)UserID.c_str(), (char*)PassWD.c_str()),但是這時候是存在危險的,因為這樣轉換後的字串其實是可以修改的(有興趣地可以自己試一試),所以我強調除非函式呼叫的時候不對引數進行修改,否則必須拷貝到一個char*上去。當然,更穩妥的辦法是無論什麼情況都拷貝到一個char*上去。同時我們也祈禱現在仍然使用C字串進行程式設計的高手們(說他們是高手一點兒也不為過,也許在我們還穿開襠褲的時候他們就開始程式設計了,哈哈…)寫的函式都比較規範,那樣我們就不必進行強制轉換了。

2.3元素存取

我們可以使用下標操作符[]和函式at()對元素包含的字元進行訪問。但是應該注意的是操作符[]並不檢查索引是否有效(有效索引0~th()),如果索引失效,會引起未定義的行為。而at()會檢查,如果使用 at()的時候索引無效,會丟擲out_of_range異常。

有一個例外不得不說,const string a;的操作符[]對索引值是th()仍然有效,其返回值是'/0'。其他的各種情況,th()索引都是無效的。舉例如下:

const string Cstr(“const string”);

string Str(“string”);

Str[3]; //ok

(3); //ok

Str[100]; //未定義的行為

(100); //throw out_of_range

Str[th()] //未定義行為

Cstr[th()] //返回 ‘/0'

(th());//throw out_of_range

(th()) ////throw out_of_range

我不贊成類似於下面的引用或指標賦值:

char& r=s[2];

char* p= &s[3];

因為一旦發生重新分配,r,p立即失效。避免的方法就是不使用。

2.4比較函式

C ++字串支援常見的比較操作符(>,>=,<,<=,==,!=),甚至支援string與C-string的比較(如 str<”hello”)。在使用>,>=,<,<=這些操作符的時候是根據“當前字元特性”將字元按字典順序進行逐一得 比較。字典排序靠前的字元小,比較的順序是從前向後比較,遇到不相等的字元就按這個位置上的兩個字元的比較結果確定兩個字串的大小。同時,string (“aaaa”) <string(aaaaa)。

另一個功能強大的比較函式是成員函式compare()。他支援多引數處理,支援用索引值和長度定位子串來進行比較。他返回一個整數來表示比較結果,返回值意義如下:0-相等 〉0-大於 <0-小於。舉例如下:

string s(“abcd”);

are(“abcd”); //返回0

are(“dcba”); //返回一個小於0的值

are(“ab”); //返回大於0的值

are(s); //相等

are(0,2,s,2,2); //用”ab”和”cd”進行比較 小於零

are(1,2,”bcx”,2); //用”bc”和”bc”比較。

怎麼樣?功能夠全的吧!什麼?還不能滿足你的胃口?好吧,那等著,後面有更個性化的比較演算法。先給個提示,使用的是STL的比較演算法。什麼?對STL一竅不通?靠,你重修吧!

2.5 更改內容

這在字串的操作中佔了很大一部分。

首先講賦值,第一個賦值方法當然是使用操作符=,新值可以是string(如:s=ns) 、c_string(如:s=”gaint”)甚至單一字元(如:s='j')。還可以使用成員函式assign(),這個成員函式可以使你更靈活的對字串賦值。還是舉例說明吧:

gn(str); //不說

gn(str,1,3);//如果str是”iamangel” 就是把”ama”賦給字串

gn(str,2,string::npos);//把字串str從索引值2開始到結尾賦給s

gn(“gaint”); //不說

gn(“nico”,5);//把'n' ‘I' ‘c' ‘o' ‘/0'賦給字串

gn(5,'x');//把五個x賦給字串

把字串清空的方法有三個:s=””;r();e();(我越來越覺得舉例比說話讓別人容易懂!)。

string提供了很多函式用於插入(insert)、刪除(erase)、替換(replace)、增加字元。

先說增加字元(這裡說的增加是在尾巴上),函式有 +=、append()、push_back()。

舉例如下:

s+=str;//加個字串

s+=”my name is jiayp”;//加個C字串

s+='a';//加個字元

nd(str);

nd(str,1,3);//不解釋了 同前面的函式引數assign的解釋

nd(str,2,string::npos)//不解釋了

nd(“my name is jiayp”);

nd(“nico”,5);

nd(5,'x');

_back(‘a');//這個函式只能增加單個字元對STL熟悉的理解起來很簡單

也許你需要在string中間的某個位置插入字串,這時候你可以用insert()函式,這個函式需要你指定一個安插位置的索引,被插入的字串將放在這個索引的後面。

rt(0,”my name”);

rt(1,str);

這種形式的insert()函式不支援傳入單個字元,這時的單個字元必須寫成字串形式(讓人噁心)。既然你覺得噁心,那就不得不繼續讀下面一段話:為了插 入單個字元,insert()函式提供了兩個對插入單個字元操作的過載函式:insert(size_type index,size_type num,chart c)和insert(iterator pos,size_type num,chart c)。其中size_type是無符號整數,iterator是char*,所以,你這麼呼叫insert函式是不行的:insert(0,1, 'j');這時候第一個引數將轉換成哪一個呢?所以你必須這麼寫:insert((string::size_type)0,1,'j')!第二種形式指 出了使用迭代器安插字元的形式,在後面會提及。順便提一下,string有很多操作是使用STL的迭代器的,他也儘量做得和STL靠近。

刪除函式erase()的形式也有好幾種(真煩!),替換函式replace()也有好幾個。

舉例吧:

string s=”il8n”;

ace(1,2,”nternationalizatio”);//從索引1開始的2個替換成後面的C_string

e(13);//從索引13開始往後全刪除

e(7,5);//從索引7開始往後刪5個

2.6提取子串和字串連線

題取子串的函式是:substr(),形式如下:

tr();//返回s的全部內容

tr(11);//從索引11往後的子串

tr(5,6);//從索引5開始6個字元

把兩個字串結合起來的函式是+。(誰不明白請致電120)

2.7輸入輸出操作

1.>> 從輸入流讀取一個string。

2.<< 把一個string寫入輸出流。

另一個函式就是getline(),他從輸入流讀取一行內容,直到遇到分行符或到了檔案尾。

2.8搜尋與查詢

查詢函式很多,功能也很強大,包括了:

find()

rfind()

find_first_of()

find_last_of()

find_first_not_of()

find_last_not_of()

這些函式返回符合搜尋條件的字元區間內的第一個字元的索引,沒找到目標就返回npos。所有的函式的引數說明如下:

第一個引數是被搜尋的物件。第二個引數(可有可無)指出string內的搜尋起點索引,第三個引數(可有可無)指出搜尋的字元個數。比較簡單,不多說不理解的可以向我提出,我再仔細的解答。當然,更加強大的STL搜尋在後面會有提及。

最後再說說npos的含義,string::npos的型別是string::size_type,所以,一旦需要把一個索引與npos相比,這個索引值必須是string::size)type型別的,更多的情況下,我們可以直接把函式和npos進行比較(如:if((“jia”)== string::npos))。

string類的建構函式:

string(const char *s); //用c字串s初始化

string(int n,char c); //用n個字元c初始化

此外,string類還支援預設建構函式和複製建構函式,如string s1;string s2="hello";都是正確的寫法。當構造的string太長而無法表達時會丟擲length_error異常

string類的字元操作:

const char &operator[](int n)const;

const char &at(int n)const;

char &operator[](int n);

char &at(int n);

operator[]和at()均返回當前字串中第n個字元的位置,但at函式提供範圍檢查,當越界時會丟擲out_of_range異常,下標運算子[]不提供檢查訪問。

const char *data()const;//返回一個非null終止的c字元陣列

const char *c_str()const;//返回一個以null終止的c字串

int copy(char *s, int n, int pos = 0) const;//把當前串中以pos開始的n個字元拷貝到以s為起始位置的字元陣列中,返回實際拷貝的數目

string的特性描述:

int capacity()const; //返回當前容量(即string中不必增加記憶體即可存放的元素個數)

int max_size()const; //返回string物件中可存放的最大字串的長度

int size()const; //返回當前字串的大小

int length()const; //返回當前字串的長度

bool empty()const; //當前字串是否為空

void resize(int len,char c);//把字串當前大小置為len,並用字元c填充不足的部分

string類的輸入輸出操作:

string類過載運算子operator>>用於輸入,同樣過載運算子operator<<用於輸出操作。

函式getline(istream &in,string &s);用於從輸入流in中讀取字串到s中,以換行符'n'分開。

string的賦值:

string &operator=(const string &s);//把字串s賦給當前字串

string &assign(const char *s);//用c型別字串s賦值

string &assign(const char *s,int n);//用c字串s開始的n個字元賦值

string &assign(const string &s);//把字串s賦給當前字串

string &assign(int n,char c);//用n個字元c賦值給當前字串

string &assign(const string &s,int start,int n);//把字串s中從start開始的n個字元賦給當前字串

string &assign(const_iterator first,const_itertor last);//把first和last迭代器之間的部分賦給字串

string的連線:

string &operator+=(const string &s);//把字串s連線到當前字串的結尾

string &append(const char *s); //把c型別字串s連線到當前字串結尾

string &append(const char *s,int n);//把c型別字串s的前n個字元連線到當前字串結尾

string &append(const string &s); //同operator+=()

string &append(const string &s,int pos,int n);//把字串s中從pos開始的n個字元連線到當前字串的結尾

string &append(int n,char c); //在當前字串結尾新增n個字元c

string &append(const_iterator first,const_iterator last);//把迭代器first和last之間的部分連線到當前字串的結尾

string的比較:

bool operator==(const string &s1,const string &s2)const;//比較兩個字串是否相等

運算子">","<",">=","<=","!="均被過載用於字串的比較;

int compare(const string &s) const;//比較當前字串和s的大小

int compare(int pos, int n,const string &s)const;//比較當前字串從pos開始的n個字元組成的字串與s的大小

int compare(int pos, int n,const string &s,int pos2,int n2)const;//比較當前字串從pos開始的n個字元組成的字串與s中pos2開始的n2個字元組成的字串的大小

int compare(const char *s) const;

int compare(int pos, int n,const char *s) const;

int compare(int pos, int n,const char *s, int pos2) const;

compare函式在>時返回1,<時返回-1,==時返回0

string的子串:

string substr(int pos = 0,int n = npos) const;//返回pos開始的n個字元組成的字串

string的交換:

void swap(string &s2); //交換當前字串與s2的值

string類的查詢函式:

int find(char c, int pos = 0) const;//從pos開始查詢字元c在當前字串的位置

int find(const char *s, int pos = 0) const;//從pos開始查詢字串s在當前串中的位置

int find(const char *s, int pos, int n) const;//從pos開始查詢字串s中前n個字元在當前串中的位置

int find(const string &s, int pos = 0) const;//從pos開始查詢字串s在當前串中的位置

//查詢成功時返回所在位置,失敗返回string::npos的值

int rfind(char c, int pos = npos) const;//從pos開始從後向前查詢字元c在當前串中的位置

int rfind(const char *s, int pos = npos) const;

int rfind(const char *s, int pos, int n = npos) const;

int rfind(const string &s,int pos = npos) const;

//從pos開始從後向前查詢字串s中前n個字元組成的字串在當前串中的位置,成功返回所在位置,失敗時返回string::npos的值

int find_first_of(char c, int pos = 0) const;//從pos開始查詢字元c第一次出現的位置

int find_first_of(const char *s, int pos = 0) const;

int find_first_of(const char *s, int pos, int n) const;

int find_first_of(const string &s,int pos = 0) const;

//從pos開始查詢當前串中第一個在s的前n個字元組成的數組裡的字元的位置。查詢失敗返回string::npos

int find_first_not_of(char c, int pos = 0) const;

int find_first_not_of(const char *s, int pos = 0) const;

int find_first_not_of(const char *s, int pos,int n) const;

int find_first_not_of(const string &s,int pos = 0) const;

//從當前串中查詢第一個不在串s中的字元出現的位置,失敗返回string::npos

int find_last_of(char c, int pos = npos) const;

int find_last_of(const char *s, int pos = npos) const;

int find_last_of(const char *s, int pos, int n = npos) const;

int find_last_of(const string &s,int pos = npos) const;

int find_last_not_of(char c, int pos = npos) const;

int find_last_not_of(const char *s, int pos = npos) const;

int find_last_not_of(const char *s, int pos, int n) const;

int find_last_not_of(const string &s,int pos = npos) const;

//find_last_of和find_last_not_of與find_first_of和find_first_not_of相似,只不過是從後向前查詢

string類的替換函式:

string &replace(int p0, int n0,const char *s);//刪除從p0開始的n0個字元,然後在p0處插入串s

string &replace(int p0, int n0,const char *s, int n);//刪除p0開始的n0個字元,然後在p0處插入字串s的前n個字元

string &replace(int p0, int n0,const string &s);//刪除從p0開始的n0個字元,然後在p0處插入串s

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

string &replace(int p0, int n0,int n, char c);//刪除p0開始的n0個字元,然後在p0處插入n個字元c

string &replace(iterator first0, iterator last0,const char *s);//把[first0,last0)之間的部分替換為字串s

string &replace(iterator first0, iterator last0,const char *s, int n);//把[first0,last0)之間的部分替換為s的前n個字元

string &replace(iterator first0, iterator last0,const string &s);//把[first0,last0)之間的部分替換為串s

string &replace(iterator first0, iterator last0,int n, char c);//把[first0,last0)之間的部分替換為n個字元c

string &replace(iterator first0, iterator last0,const_iterator first, const_iterator last);//把[first0,last0)之間的部分替換成[first,last)之間的字串

string類的插入函式:

string &insert(int p0, const char *s);

string &insert(int p0, const char *s, int n);

string &insert(int p0,const string &s);

string &insert(int p0,const string &s, int pos, int n);

//前4個函式在p0位置插入字串s中pos開始的前n個字元

string &insert(int p0, int n, char c);//此函式在p0處插入n個字元c

iterator insert(iterator it, char c);//在it處插入字元c,返回插入後迭代器的位置

void insert(iterator it, const_iterator first, const_iterator last);//在it處插入[first,last)之間的字元

void insert(iterator it, int n, char c);//在it處插入n個字元c

string類的刪除函式

iterator erase(iterator first, iterator last);//刪除[first,last)之間的所有字元,返回刪除後迭代器的位置

iterator erase(iterator it);//刪除it指向的字元,返回刪除後迭代器的位置

string &erase(int pos = 0, int n = npos);//刪除pos開始的n個字元,返回修改後的字串

string類的迭代器處理:

string類提供了向前和向後遍歷的迭代器iterator,迭代器提供了訪問各個字元的語法,類似於指標操作,迭代器不檢查範圍。

用string::iterator或string::const_iterator宣告迭代器變數,const_iterator不允許改變迭代的內容。常用迭代器函式有:

const_iterator begin()const;

iterator begin(); //返回string的起始位置

const_iterator end()const;

iterator end(); //返回string的最後一個字元後面的位置

const_iterator rbegin()const;

iterator rbegin(); //返回string的最後一個字元的位置

const_iterator rend()const;

iterator rend(); //返回string第一個字元位置的前面

rbegin和rend用於從後向前的迭代訪問,通過設定迭代器string::reverse_iterator,string::const_reverse_iterator實現

字串流處理:

通過定義ostringstream和istringstream變數實現,<sstream>標頭檔案中

例如:

string input("hello,this is a test");

istringstream is(input);

string s1,s2,s3,s4;

is>>s1>>s2>>s3>>s4;//s1="hello,this",s2="is",s3="a",s4="test"

ostringstream os;

os<<s1<<s2<<s3<<s4;

cout<<();