std::string詳解
之所以拋棄char*的字串而選用C++標準程式庫中的string類,是因為他和前者比較起來,不必 擔心記憶體是否足夠、字串長度等等,而且作為一個類出現,他集成的操作函式足以完成我們大多數情況下(甚至是100%)的需要,我們可以用 = 進行賦值操作,== 進行比較,+ 做串聯(是不是很簡單?),我們盡可以把它看成是C++的基本資料型別,
標準模板庫(STL)提供了一個std::string類,其是std::basic_string的一個特化,它是一個容器類,可把字串當作普通型別來使用,并支持比較、連接、遍歷、STL演算法、復制、賦值等等操作,這個類定義在
實作原理
1.宣告一個C++字串,初始化
std::string類的建構式宣告一個字串變數很簡單:string Str;
這樣我們就宣告了一個字串變數,但既然是一個類,就有建構式和解構式,上面的宣告沒有傳入引數,所以就直接使用了string的默認的建構式,這個函式所作的就是把Str初始化為一個空字串,String類的建構式和解構式如下:
- string s(); //生成一個空字串s
- string s(str) //拷貝建構式 生成str的復制品string(const string& str)
- string s(const char *s) //將C字串作為s的初值
- string s(const char* cstr, size_type n) //使用字串str的前n個字符初始化作為字串s的初值,
- string s(str,stridx) //將字串str內"始于位置stridx"的部分當作字串的初值
- string s(const string& str, size_type pos,strlen) //將字串str內"始于pos且長度頂多strlen"的部分作為字串的初值
- string s(int num,char c) //生成一個字串,包含num個c字符
- string s(begin,end) //以區間beg;end(不包含end)內的字符作為字串s的初值,即迭代器間的值,
- s.~string() //銷毀所有字符,釋放記憶體
- 注意:當構造的string太長而無法表達時會拋出length_error例外
- 當指定拷貝的長度大于被拷貝字串的長度時,是將字串對應位置中剩余的內容全部拷貝,
2.字串操作函式
1.賦以新值 = ,assign( )
第一個賦值方法當然是使用運算子=,新值可以是string(如:s=ns) 、c_string(如:s="gaint")甚至單一字符(如:s=’j’),
還可以使用成員函式assign(),這個成員函式可以使你更靈活的對字串賦值,注意和string的構造初始化賦值等函式基本類似,只是這個是賦予新值,
s.assign(str);
s.assign(str,1,3);//如果str是"iamangel" 就是把"ama"賦給字串
s.assign(str,2,string::npos);//把字串str從索引值2開始到結尾賦給s
s.assign("gaint");
s.assign("nico",3);//把’n’ ‘I’ ‘c’賦給字串
s.assign("nicoafdad",2,5);//從二開始數五個
s.assign(5,’x’);//把五個x賦給字串
2.兩個字串關系:交換swap( ) 比較字串 ==,!=,< , <= , > , >= , ,compare( )
a.swap(b); //結果為 b="12345678"; a="ABCD";swap會導致迭代器失效
C ++字串支持常見的比較運算子(>,>=,<,<=,==,!=),甚至支持string與C-string的比較(如 str<"hello"),在使用>,>=,<,<=這些運算子的時候是根據"當前字符特性"將字符按字典順序進行逐一得 比較,字典排序靠前的字符小,比較的順序是從前向后比較,遇到不相等的字符就按這個位置上的兩個字符的比較結果確定兩個字串的大小,同時,string ("aaaa") <string(aaaaa),
另一個功能強大的比較函式是成員函式compare(),他支持多引數處理,支持用索引值和長度定位子串來進行比較,他回傳一個整數來表示比較結果,回傳值意義如下:0-相等 〉0-大于 <0-小于,舉例如下:
string字串使用方法都類似
string s("abcd");
s.compare("abcd"); //回傳0
s.compare("dcba"); //回傳一個小于0的值
s.compare("ab"); //回傳大于0的值
s.compare(s); //相等
auto number = b.compare(0,4,"1234efgh",4,4); //結果為 number=0; //字串b從下標為0的地方開始的后四個字符是efgh,字串"1234efgh"從下標為4的字符開始的后4個字符是efgh,所以相等
s.compare(1,2,"bcx",2); //用"bc"和"bc"比較,
3.添加插入:在尾部添加字符 += , append() ,push_back( ) 插入字符insert( ) 串聯字串 +
append和asign和string初始化都差不多,這個是追加,+=和等于也類似的關系
s+=str;//加個字串
s+="my name is jiayp";//加個C字串
s+=’a’;//加個字符
s.append(str);
s.append(str,1,3);//不解釋了 同前面的函式引數assign的解釋
s.append(str,2,string::npos)//不解釋了
s.append("my name is jiayp");
s.append("nico",5);
s.append(5,’x’);
s.push_back(‘a’);//這個函式只能增加單個字符
也許你需要在string中間的某個位置插入字串,這時候你可以用insert()函式,這個函式需要你指定一個安插位置的索引,被插入的字串將放在這個索引的后面,
string a = "1234";
string b = "5678";
1.在string字串某一個位置上插入另一個(string)字串
insert(int,string&);
a.insert(0, b); //結果為 a="56781234";
a.insert(2, b); //結果為 a="12567834";
insert(int,const char*);
a.insert(3,"abcd");//結果為 a="123abcd4";
2.在string字串某一個位置上插入另一個字串的前n個字符
insert(int,const char*,int);
a.insert(1,"abcd",2); //結果為 a="1ab234";
3.在string字串某一位置上插入另一個string字串(從下標為n的位置開始到結束)
insert(int,string&,int);
a.insert(1,b,2); //結果為 a="178234";
4.在string字串某一位置上插入另一個(string)字串(從下標為n的位置開始連續m個字符)
insert(int,string&,int,int);
a.insert(2,b,1,2); //結果為 a="126734";
a.insert(0,b,0,3); //結果為 a="5671234";
insert(int,const char*,int,int);
a.insert(2,"5678",1,2); //結果為 a="126734";
5.在字串中插入n個字符
insert(int,int,const char);
a.insert(2,5,'k'); //結果為 a="12kkkkk34";
insert(iterator,const char);
a.insert(a.begin()+3,'k'); //結果為 a="123k4";
insert(iterator,int,const char);
a.insert(a.begin()+3,10,'k'); //結果為 a="123kkkkkkkkkk4";
6.在字串某個位置插入另一個字串的某一個區間字符
insert(iterator,const_iterator_first,const_iterator_last);
a.insert(a.begin() + 1, b.begin() + 1, b.end() - 1);//結果為 a="167234";
4.取改 單一字符 [ ], at() 替換字符replace()
可以使用下標運算子[]和函式at()對元素包含的字符進行訪問,但是應該注意的是運算子[]并不檢查索引是否有效(有效索引0~str.length()),如果索引失效,會引起未定義的行為,而at()會檢查,如果使用 at()的時候索引無效,會拋出out_of_range例外,
1.獲取string字串某一個字符 auto s=a.at(1); 2.修改string字串某一個字符 a.at(2)='1';
使用[]同理;還有stl的迭代器和front(),back()也可以
不贊成類似于下面的參考或指標賦值:
char& r=s[2];
char* p= &s[3];
因為一旦發生重新分配,r,p立即失效,避免的方法就是不使用,
遍歷所有字符,這可由C風格的索引或STL迭代子來完成(如果無需修改,應使用const_iterator),
std::string name = "marius";
for(size_t i = 0; i < name.length(); ++i)
std::cout << name[i];
for(std::string::const_iterator cit = name.begin(); cit != name.end(); ++cit)
std::cout << *cit;
for(std::string::iterator it = name.begin();it != name.end(); ++it)
*it = toupper(*it);
string s="il8n";
s.replace(1,2,"nternationalizatio");//從索引1開始的2個替換成后面的C_string
std :: string類的替換函式
函式1:std::string & replace ( (size_type pos1, size_type n1, const std::string & str, size_type pos2 = 0, size_type n2 = npos )) ;
s1.replace(1, 3, "123456", 2, 4); //用 "123456" 的子串(2,4) 替換 s1 的子串(1,3)
該函式的作用:使用str字串從位置pos2開始的n2個字符,替換當前字串從pos1位置開始處的n1個字符,即該函式將當前字串從pos1開始的n1個字符全部洗掉,然后再用str整個字串或者str從pos2開始的n2個字符,從pos1位置開始填入到當前字串中,
提醒:如果n1或者n2的數值超出了對應字串的長度,以實際長度為準,不會出現訪問越界的情況,
注意:函式(1~4)
a、如果pos1指定的位置超出當前字串的范圍,拋出std::out_of_range例外,不捕捉將導致coredump,
b、如果pos2指定的位置超出替換字串str的范圍,拋出std::out_of_range例外,不捕捉將導致coredump,
函式2:std::string& replace(size_type pos, size_type n1, const char * s, size_type n2);
該函式的作用:使用字串s的前n2個字符,替換當前字串從pos位置開始處的n1個字符,即函式將當前字串從pos開始的n1個字符全部洗掉,然后再用字串s的前n2個字符填入到當前字串中,類似于函式1的pos2等于0,必須指定n2的這種情況,但也有一點的差別,下面會注意里描述這種差別,
a.replace(6, 3, "THJKL", 2); //結果為 a="1234abTH678efgh";
函式3:std::string& replace(size_type pos, size_type n1, const char* s);
s2.replace(n, 5, "XXX"); //將子串(n,5)替換為"XXX"
該函式的作用:使用以''為結尾的字串s,替換當前字串從pos位置開始處的n1個字符,即函式將當前字串從pos開始的n1個字符全部洗掉,然后再用字串s從開始到以''結束的所有字符,從pos位置開始填入到當前字串中,
函式4:std::string& replace(size_type pos, size_type n1, size_type n2, char c);
該函式的作用:使用n2個c表示的字符,替換當前字串從pos位置開始處的n1個字符,即函式將當前字串從pos開始的n1個字符全部洗掉,然后再用n2個c字符,從pos位置開始填入到當前字串中,
s2.replace(2, 3, 5, '0'); //用 5 個 '0' 替換子串(2,3)
函式5:std::string& replace((iterator i1, iterator i2, const std:: string& str));
該函式的作用:使用字串str,替換當前字串[i1,i2)之間的字符,
a.replace(a.begin()+5,a.end()-3,b); //結果為 a="1234aABCDfgh";
函式6:std::string& replace(iterator i1, iterator i2, const char* s, size_type n);
該函式的作用:使用字串s的前n個字符,替換當前字串[i1,i2)之間的字符,
a.replace(a.begin() + 6, a.end() - 3, "THJKL", 2);//結果為 a="1234abTHfgh";
函式7:std::string& replace(iterator i1, iterator i2, const char* s);
該函式的作用:使用以''結尾的字串s,替換當前字串[i1,i2)之間的字符,
a.replace(a.begin()+3,a.begin()+6,"替換"); //結果為 a="123替換cd5678efgh";
函式8:std::string& replace(iterator i1, iterator i2, size_type n, char c);
該函式的作用:使用n個c表示的字符,替換當前字串[i1,i2)之間的字符,
a.replace(a.begin()+6, a.end()-3, 5, '>');
5.將某值寫入和寫出stream >>,getline(),<<
1.>> 從輸入流讀取一個string
2.<< 把一個string寫入輸出流,
3. 另一個函式就是getline(),他從輸入流讀取一行內容,直到遇到分行符或到了檔案尾,istream& getline (istream& is, string& str);std::getline(std::cin, s);getline就可以實作輸入整行字串,如果需要輸入多行,用一個while嵌套即可:while( getline() )
6.洗掉全部字符clear() 洗掉nStart—nEnd位置字符erase(int nStart,int nEnd)
把字串清空的方法有三個:s="";s.clear();s.erase();
在字串末尾洗掉一個字符 a.pop_back(); //結果為 a="12";
1.洗掉所有字符
a.erase(); //結果為 a="";
2.從字串的某一個位置開始洗掉
a.erase(n) //從字串的第n個字符開始洗掉
a.erase(3); //結果為 a="123";
a.erase(5); //結果為 a="12345";
a.erase(0); //等同于a.erase() a="";
3.從字串的某一個位置開始,向后洗掉m個字符
a.erase(n,m); //從字符的第n個字符開始洗掉m個字符
a.erase(2,3); //結果為 a="126789";
a.erase(4,1); //結果為 a="12346789";
4.洗掉迭代器位置處的字符,并回傳下一個字符的迭代器
auot iter=a.erase(a.begin()+1); //結果為 a="13456789";
cout<<*iter<<endl; //結果為 *iter=3
5.洗掉迭代器所指向的區間,并回傳下一個字符的迭代器 auto iter=a.erase(a.begin()+1,a.end()-2);//結果為 a="189";
cout<<*iter<,endl; //結果為 *iter=8;
6.洗掉字符時常常與find()函式配合使用(find()函式的用法會在以后寫出)
a.erase(a.find("56"),2); //結果為 a="1234789";
7.stl相關begin() end() rbegin() rend() front和back
std::string name = "marius";
// 使字串全為大寫
std::transform(name.begin(), name.end(), name.begin(),toupper);
std::string name = "marius";
// 升序排列字串
std::sort(name.begin(), name.end());
std::string name = "marius";
// 反轉字串
std::reverse(name.begin(), name.end());
bool iswhitespace(char ch){
returnch == ' ' || ch == 't' || ch == 'v' ||
ch == 'r' || ch == 'n';
}
std::string name = " marius";
// 洗掉空白字符
std::string::iterator newend = std::remove_if(name.begin(), name.end(), iswhitespace);
name.erase(newend);
string a="abcd";
1.獲取字串最后一個字符
auto b=a.back(); //結果為 b='d';
2.修改字串最后一個字符
a.back()='!'; //結果為 a="abc!";
3.獲取字串第一個字符
auto b=a.front(); //結果為 b='a';
4.修改字串第一個字符
a.front()='!'; //結果為 a="!bcd";
string::reverse_iterator rit = s.rbegin();//取開頭是呼叫rbegin介面
8.查找函式和回傳某個子字串substr()
find(),rfind(),find_first_of(),find_last_of(),find_first_not_of(),find_last_not_of()
這些函式回傳符合搜索條件的字符區間內的第一個字符的索引,沒找到目標就回傳npos,所有的函式的引數說明:
第一個引數是被搜尋的物件,第二個引數(可有可無)指出string內的搜尋起點索引,第三個引數(可有可無)指出搜尋的字符個數,
find()與rfind()
string a="123456789abcdefgab";
string b="789abc";
如果找不到則回傳的值為string::npos
/*if(a.find('k')==string::npos){cout<<"沒有找到"<<endl;}*/
1.在字串中查找某一個字符
(1).從字串開始位置開始查找
auto s=a.find('a'); //結果為 s=9;
//表明a在字串中從左向右第一次出現的位置的下標為9
(2).從字串某一個位置開始查找
auto s=a.find('a',11); //結果為 s=16
//從字串下標為11的地方開始查找字符
2.在字串中查找某一個子串
(1).從字串開始位置開始查找
auto s=a.find("9a");//結果為 s=8;
//表明9a子串的第一個字符在字串中從左向右第一次出現的位置下標為8
auto s=a.find(b); //結果為 s=6;
(2).從字串某一個位置開始查找
auto s=a.find("ab",11); //結果為 s=16
//從字符下標為11的地方開始向后查找
3.在字串中查找子串的前n個字符
auto s=a.find("abcd",11,2); //結果為 s=16;
//解釋:在字串a中查找,子串"abcd"的前2個字符即在字串a中查找"ab"
//注意 在這個多載函式中,第一個引數只能是char* 型別,而不能是string型別
4.find()與rfind()的區別
find()是字串從前向后查找,rfind()是字串從后向前查找,其他的用法與find()函式類似
find_first_of()與find_last_of()
string a="123456789abcdefgh";
1.在字串中查找某一個字符
auto s=a.find_first_of('5');//結果為 s=4;
auto s=a.find_first_of('5',5); //沒有查找到 s=string::npos;
//如果查找某一個字符,與find()函式類似
2.在字串中查找子串
//此時與find()函式不同,find()函式是查找子串,
//而find_first_of()函式是查找字串a中含有的任意子串的字符
auto s=a.find_first_of("8a"); //結果為 s=7;
auto s=a.find_first_of("8a",1); //結果為 s=7;
//在字串a中查找最早出現的字符'8'或者'a';
auto s=a,find("8a"); //結果是找不到
auto s=a,find("8a",1); //結果是找不到
//find()函式查找子串必須是相連的,而find_first_of()不需要,只要字串中含有子串的字就可以
/*重要
*find_first_of()函式在字串中查找子串中出現的任意字符,比如在字串 "12abc"中查找子串"1k",1在字串"12abc"中出現過,所以可以找到
*find()函式在字串"12abc"中查找"1k",則查找不到,它查找的必須是"1k"這兩個相連的字符
*/
3.find_first_of()與find_last_of()的區別
find_first_of()是從前向后查找,而find_last_of()是從后向前查找,其他的用法與find_first_of()函式類似,
find_first_not_of()與find_last_not_of()
find_first_not_of()與find_first_of()功能正好相反,不懂得可以先看我寫的find_first_of()函式功能詳解
find_firat_of()函式是在字串中查找子串出現過的任意字符,也可以所字串與子串都有的字符,
find_first_not_of()函式是在字串中查找子串沒有出現過的任意字符,也可以說是,字串中有而子串中沒有的字符
//以上查找的結果都是最先出現的那個字符的下標
//例
string a="12345";
auto s=a.find_first_not_of("1238"); //結果為 s=3;
//a字串中有,而子串沒有的是"45",而'4'字符是最先出現的,它的下標為3
find_first_not_of(str,n);
//str是子串,n是從下標為n的字符開始查找
find_first_not_of(str,n,m);
//str是子串,n是從下標為n的字符開始查找
//m是只看str子串的前m位字符
find_first_not_of()與find_last_not_of()查找順序正好相反,
find_first_not_of()是從前向后,find_last_not_of()是從后向前查找
//如果以上看不懂的話建議先從find(),rfina()函式看起,之后再看find_first_of()與find_last_of(),最后看find_first_not_of()與find_last_not_of()
最后再說說npos的含義,string::npos的型別是string::size_type,所以,一旦需要把一個索引與npos相比,這個索引值必須是string::size)type型別的,更多的情況下,我們可以直接把函式和npos進行比較(如:if(s.find("jia")== string::npos)),
s.substr();//回傳s的全部內容
s.substr(11);//從索引11往后的子串
s.substr(5,6);//從索引5開始6個字符
// 獲取file的后綴
void Teststring1(){
string file("string.cpp");
size_t pos = file.rfind('.');
string suffix = file.substr(pos);
cout << suffix << endl;
}
// 取出url中的域名
void Teststring2(){
string url("http://www.cplusplus.com/reference/string/string/find/");
cout << url << endl;
size_t start = url.find("://");
//如果沒有://,說明是無效協議
if (start == string::npos) {
cout << "invalid url" << endl;
return;
}
else{
string tmp = url.substr(0, start);//取出協議
cout << tmp << endl;
}
//找到域名的起始位置
start += 3;
//查找域名的結尾
size_t finish = url.find('/', start);
//取出域名
string address = url.substr(start, finish - start);
cout << address << endl;
}
9.回傳字符數量size(),length() 回傳字符的可能最大個數max_size() 判斷字串是否為空 empty() 回傳重新分配之前的字符容量capacity() 保留一定量記憶體以容納一定數量的字符reserve()
auto s=a.empty(); //結果為 s=false;
- size()和length(),他們等效,Empty()用來檢查字串是否為空,
- max_size() 這個大小是指當前C++字串最多能包含的字符數,很可能和機器本身的限制或者字串所在位置連續記憶體的大小有關系,我們一般情況下不用關心他,應該大小足夠我們用的,
- capacity()重新分配記憶體之前 string所能包含的最大字符數,這里另一個需要指出的是reserve()函式,這個函式為string重新分配記憶體,重新分配的大小由其引數決定, 默認引數為0,這時候會對string進行非強制性縮減,
-
a.reserve(20); reserve(size_t);可以調整string的空間, 如果size_t大于capacity的容量,則capacity按n*16-1擴大到比size_t 如果size_t小于capacity,則capacity不變 -
a.resize(40); resize(size_t);可以調整string的空間, 可以改變string size的大小,并且capacity隨size變大而變大,但是不會減小,當size縮小后,字符超出的部分會被裁剪掉, a.resize(40,'A'); 擴充size后可以輸入預定字符進行填充 //結果為 a="1234AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
10.與c語言字串: 將某值賦值為一個C_string,copy() 將內容以C_string回傳 c_str() 將內容以字符陣列形式回傳data()
data()以字符陣列的形式回傳字串內容,但并不添加’\0’,c_str()回傳一個以‘\0’結尾的字符陣列,而copy()則把字串的內容復制或寫入既有的c_string或字符陣列內,C++字串并不以’\0’結尾char*為C編程中最常用的字串指標,一般以’\0′為結束標志;
char *str = new char[64];
string a="12345abcdefg6789";
str[a.copy(str,7,5)]='\0'; // 結果為 str="abcdefg";
str[a.copy(str,7)]='\0'; // 結果為 str="12345ab";
delete[]str; /*注意 *copy的第2,3個引數不能大于字串str所能容納的最長字串長度 */
str=a.c_str(); str=a.data();//a改變,str也隨之改變
//可以生成一個const char* 的指標,可以指向一個空字符終止的地址, const char* str=nullptr;
c語言中字串在stdlib.h中有atoi和strtod等字串轉為數字的函式而string可以自己定義萬能轉換函式
* 轉string * *為i,l,f,d
string *tos(* i){ // 改一下函式名,改一下型別,搞定
ostringstream os;
os<<i;
string result;
istringstream is(os.str());
is>>result;
return result;
}//將 * 換成想要的型別就可以執行 * 轉 string
*string *
* sto*(string str){ // 改一下函式名,變數型別,搞定
* result;
istringstream is(str);
is >> result;
return result;
}//將 * 換成想要的型別就可以執行 string 轉 *
//也可以多載函式,達到萬能函式轉換
//記得包含頭檔案 #include <sstream>
//總結:使用 string 流和標準 io 流其實本身就是流,一個原理的,不同呼叫方法,
注意:前導0,長度
string常見操作
- 把字串轉換成整數
/*首先,這個題不考慮字母*/ /*那就簡單多了,只考慮數字,遇到其他情況直接回傳-1就行了*/ class Solution { public: int StrToInt(string str) { int ans = 0;int isplus = 1; for(char ch:str){ if(isalpha(ch)){ return 0; }if (ch == '+' || ch =='-'){ isplus = (ch == '+') ? 1 : -1; }if(isdigit(ch)){ ans = ans*10+ch-'0'; } }return isplus*ans; } }; - 字串相加("123"+"23"="146")
string addStrings(string num1, string num2) {
string str;
int cur = 0, i = num1.size()-1, j = num2.size()-1;
while (i >= 0 || j >= 0 || cur != 0) {
if (i >= 0) cur += num1[i--] - '0';
if (j >= 0) cur += num2[j--] - '0';
str += to_string (cur % 10);//將int轉換位string;string num = to_string(sum);
cur /= 10;
}
reverse(str.begin(), str.end());
return str;
string addStrings(string num1, string num2) {
int i = num1.length() - 1, j = num2.length() - 1, add = 0;
string ans = "";
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1[i] - '0' : 0;
int y = j >= 0 ? num2[j] - '0' : 0;
int result = x + y + add;
ans.push_back('0' + result % 10);
add = result / 10; i -= 1; j -= 1;
}
// 計算完以后的答案需要翻轉過來
reverse(ans.begin(), ans.end());
return ans;
}
}
const string a;的運算子[]對索引值是a.length()仍然有效,其回傳值是’’,其他的各種情況,a.length()索引都是無效的,舉例如下:
const string Cstr("const string");
string Str("string");
Str[3]; //ok
Str.at(3); //ok
Str[100]; //未定義的行為
Str.at(100); //throw out_of_range
Str[Str.length()] //未定義行為
Cstr[Cstr.length()] //回傳 ‘’
Str.at(Str.length());//throw out_of_range
Cstr.at(Cstr.length()) throw out_of_range
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/543990.html
標籤:其他
