string如何在C++中使用?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。

string是C++標(biāo)準(zhǔn)庫的一個(gè)重要的部分,主要用于字符串處理。可以使用輸入輸出流方式直接進(jìn)行操作,也可以通過文件等手段進(jìn)行操作。同時(shí)C++的算法庫對(duì)string也有著很好的支持,而且string還和c語言的字符串之間有著良好的接口。雖然也有一些弊端,但是瑕不掩瑜。
其中使用的代碼多數(shù)都是來自cpp官網(wǎng),因?yàn)槔臃浅H?/p>
聲明和初始化方法:
想使用string首先要在頭文件當(dāng)中加入< string >
聲明方式也很簡單
聲明:
string s;//聲明一個(gè)string 對(duì)象 string ss[10];//聲明一個(gè)string對(duì)象的數(shù)組
初始化:
使用等號(hào)的初始化叫做拷貝初始化,不使用等號(hào)的初始化叫做直接初始化。
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string s;//默認(rèn)初始化,一個(gè)空字符串
string s1("ssss");//s1是字面值“ssss”的副本
string s2(s1);//s2是s1的副本
string s3=s2;//s3是s2的副本
string s4(10,'c');//把s4初始化
string s5="hiya";//拷貝初始化
string s6=string(10,'c');//拷貝初始化,生成一個(gè)初始化好的對(duì)象,拷貝給s6
//string s(cp,n)
char cs[]="12345";
string s7(cs,3);//復(fù)制字符串cs的前3個(gè)字符到s當(dāng)中
//string s(s2,pos2)
string s8="asac";
string s9(s8,2);//從s2的第二個(gè)字符開始拷貝,不能超過s2的size
//string s(s2,pos2,len2)
string s10="qweqweqweq";
string s11(s10,3,4);//s4是s3從下標(biāo)3開始4個(gè)字符的拷貝,超過s3.size出現(xiàn)未定義
return 0;
}字符串處理:
substr操作:
注意substr沒有迭代器作為參數(shù)的操作
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string s="abcdefg";
//s.substr(pos1,n)返回字符串位置為pos1后面的n個(gè)字符組成的串
string s2=s.substr(1,5);//bcdef
//s.substr(pos)//得到一個(gè)pos到結(jié)尾的串
string s3=s.substr(4);//efg
return 0;
}如果輸入的位置超過字符的長度,會(huì)拋出一個(gè)out_of_range的異常
insert操作:
代碼來自cpp官網(wǎng),經(jīng)過自己的整理
注意用迭代器當(dāng)參數(shù)和無符號(hào)數(shù)當(dāng)參數(shù)的區(qū)別
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string str="to be question";
string str2="the ";
string str3="or not to be";
string::iterator it;
//s.insert(pos,str)//在s的pos位置插入str
str.insert(6,str2); // to be the question
//s.insert(pos,str,a,n)在s的pos位置插入str中插入位置a到后面的n個(gè)字符
str.insert(6,str3,3,4); // to be not the question
//s.insert(pos,cstr,n)//在pos位置插入cstr字符串從開始到后面的n個(gè)字符
str.insert(10,"that is cool",8); // to be not that is the question
//s.insert(pos,cstr)在s的pos位置插入cstr
str.insert(10,"to be "); // to be not to be that is the question
//s.insert(pos,n,ch)在s.pos位置上面插入n個(gè)ch
str.insert(15,1,':'); // to be not to be: that is the question
//s.insert(s.it,ch)在s的it指向位置前面插入一個(gè)字符ch,返回新插入的位置的迭代器
it = str.insert(str.begin()+5,','); // to be, not to be: that is the question
//s.insert(s.it,n,ch)//在s的it所指向位置的前面插入n個(gè)ch
str.insert (str.end(),3,'.'); // to be, not to be: that is the question...
//s.insert(it,str.ita,str.itb)在it所指向的位置的前面插入[ita,itb)的字符串
str.insert (it+2,str3.begin(),str3.begin()+3); // to be, or not to be: that is the question...
return 0;
}erase操作:
用來執(zhí)行刪除操作
刪除操作有三種
指定pos和len,其中pos為為起始位置,pos以及后面len-1個(gè)字符串都刪除
迭代器,刪除迭代器指向的字符
迭代器范圍,刪除這一范圍的字符串,范圍左閉右開
代碼來自cpp官網(wǎng)
#include <iostream>
#include <string>
int main ()
{
std::string str ("This is an example sentence.");
std::cout << str << '\n';
// "This is an example sentence."
str.erase (10,8); // ^^^^^^^^
//直接指定刪除的字符串位置第十個(gè)后面的8個(gè)字符
std::cout << str << '\n';
// "This is an sentence."
str.erase (str.begin()+9);// ^
//刪除迭代器指向的字符
std::cout << str << '\n';
// "This is a sentence."
// ^^^^^
str.erase (str.begin()+5, str.end()-9);
//刪除迭代器范圍的字符
std::cout << str << '\n';
// "This sentence."
return 0;
}append和replace操作:
append函數(shù)可以用來在字符串的末尾追加字符和字符串。由于string重載了運(yùn)算符,也可以用+=操作實(shí)現(xiàn)
repalce顧名思義,就是替換的意思,先刪除,后增加。
代碼來自cpp官網(wǎng),附上自己的解釋
#include <iostream>
#include <string>
int main ()
{
std::string str;
std::string str2="Writing ";
std::string str3="print 10 and then 5 more";
//直接追加一個(gè)str2的字符串
str.append(str2); // "Writing "
//后面追加str3第6個(gè)字符開始的3個(gè)字符串
str.append(str3,6,3); // "10 "
//追加字符串形參的前5個(gè)字符
str.append("dots are cool",5); // "dots "
//直接添加
str.append("here: "); // "here: "
//添加10個(gè)'.'
str.append(10u,'.'); // ".........."
//添加str3迭代器范圍的字符串
str.append(str3.begin()+8,str3.end()); // " and then 5 more"
//最后這個(gè)比較特殊,意思是添加5個(gè)'A',實(shí)際上參數(shù)里面的65對(duì)應(yīng)的asc碼就是65
str.append<int>(5,65); // "....."
//字符串追加也可以用重載運(yùn)算符實(shí)現(xiàn)
str+="lalala";
std::cout << str << '\n';
return 0;
}replace的使用方法,replace支持使用無符號(hào)整數(shù)尋找位置,也支持用迭代器尋找位置
#include <iostream>
#include <string>
int main ()
{
std::string base="this is a test string.";
std::string str2="n example";
std::string str3="sample phrase";
std::string str4="useful.";
// replace signatures used in the same order as described above:
// Using positions: 0123456789*123456789*12345
std::string str=base; // "this is a test string."
//第9個(gè)字符以及后面的4個(gè)字符被str2代替
str.replace(9,5,str2); // "this is an example string." (1)
//第19個(gè)字符串以及后面的5個(gè)字符用str的第7個(gè)字符以及后面的5個(gè)字符代替
str.replace(19,6,str3,7,6); // "this is an example phrase." (2)
//第8個(gè)字符以及后面的9個(gè)字符用字符串參數(shù)代替
str.replace(8,10,"just a"); // "this is just a phrase." (3)
//第8個(gè)字符以及后面的5個(gè)字符用字符串參數(shù)的前7個(gè)字符替換
str.replace(8,6,"a shorty",7); // "this is a short phrase." (4)
//第22以及后面的0個(gè)字符用3個(gè)嘆號(hào)替換
str.replace(22,1,3,'!'); // "this is a short phrase!!!" (5)
//迭代器的原理同上
// Using iterators: 0123456789*123456789*
str.replace(str.begin(),str.end()-3,str3); // "sample phrase!!!" (1)
str.replace(str.begin(),str.begin()+6,"replace"); // "replace phrase!!!" (3)
str.replace(str.begin()+8,str.begin()+14,"is coolness",7); // "replace is cool!!!" (4)
str.replace(str.begin()+12,str.end()-4,4,'o'); // "replace is cooool!!!" (5)
str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful." (6)
std::cout << str << '\n';
return 0;
}以上的replace操作可以用insert和erase的操作組合替換,但是replace操作更加方便。
assign操作:
assign操作在一起列容器當(dāng)中都存在,比如vector等等。是一個(gè)很基本的操作函數(shù),string使用assign可以靈活的對(duì)其進(jìn)行賦值。
代碼來自cpp官網(wǎng)
#include <iostream>
#include <string>
int main ()
{
std::string str;
std::string base="The quick brown fox jumps over a lazy dog.";
// used in the same order as described above:
//直接把base賦值給str
str.assign(base);
std::cout << str << '\n';
//把base第10個(gè)字符以及后面的8個(gè)字符賦給str
str.assign(base,10,9);
std::cout << str << '\n'; // "brown fox"
//把參數(shù)中的0到6個(gè)字符串賦給str
str.assign("pangrams are cool",7);
std::cout << str << '\n'; // "pangram"
//直接使用參數(shù)賦值
str.assign("c-string");
std::cout << str << '\n'; // "c-string"
//給str賦值10個(gè)'*'字符
str.assign(10,'*');
std::cout << str << '\n'; // "**********"
//賦值是10個(gè)'-'
str.assign<int>(10,0x2D);
std::cout << str << '\n'; // "----------"
//指定base迭代器范圍的字符串
str.assign(base.begin()+16,base.end()-12);
std::cout << str << '\n'; // "fox jumps over"
return 0;
}string的搜索操作:
string類中提供了很多性能優(yōu)秀,使用方便的成員方法。而且在泛型算法當(dāng)中也有很多實(shí)用的技巧。
find和rfind函數(shù):
find函數(shù)主要是查找一個(gè)字符串是否在調(diào)用的字符串中出現(xiàn)過,大小寫敏感。
代碼來自cpp官網(wǎng)
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");
// different member versions of find in the same order as above:
//在str當(dāng)中查找第一個(gè)出現(xiàn)的needle,找到則返回出現(xiàn)的位置,否則返回結(jié)尾
std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';
//在str當(dāng)中,從第found+1的位置開始查找參數(shù)字符串的前6個(gè)字符
found=str.find("needles are small",found+1,6);
if (found!=std::string::npos)
std::cout << "second 'needle' found at: " << found << '\n';
//在str當(dāng)中查找參數(shù)中的字符串
found=str.find("haystack");
if (found!=std::string::npos)
std::cout << "'haystack' also found at: " << found << '\n';
//查找一個(gè)字符
found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';
//組合使用,把str2用參數(shù)表中的字符串代替
// let's replace the first needle:
str.replace(str.find(str2),str2.length(),"preposition");
std::cout << str << '\n';
return 0;
}rfind函數(shù)就是找最后一個(gè)出現(xiàn)的匹配字符串,返回的位置仍然是從前往后數(shù)的。
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
std::string str ("The sixth sick sheik's sixth sheep's sick.");
std::string key ("sixth");// ^
//rfind是找最后一個(gè)出現(xiàn)的匹配字符串
std::size_t found = str.rfind(key);
if (found!=std::string::npos)
{
cout<<found<<endl;//輸出23
str.replace (found,key.length(),"seventh");//找到的sixth替換成seventh
}
std::cout << str << '\n';
return 0;
}查找的效率非常高,我沒看過stl源碼剖析,但是感覺是用kmp實(shí)現(xiàn)的。呵呵,可以自己寫一個(gè)。
find_….of函數(shù):
find_first_of(args) 查找args中任何一個(gè)字符第一次出現(xiàn)的位置
find_last_of(args) 最后一個(gè)出現(xiàn)的位置
find_fist_not_of(args) 查找第一個(gè)不在args中的字符
find_last_not_of 查找最后一個(gè)不在args中出現(xiàn)的字符
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
std::string str1 ("Please, replace the vowels in this sentence by asterisks.");
std::size_t found1 = str1.find_first_of("aeiou");
//把所有元音找出來用*代替
while (found1!=std::string::npos)
{
str1[found1]='*';
found1=str1.find_first_of("aeiou",found1+1);
}
std::cout << str1 << '\n';
//在str2中找到第一個(gè)不是消協(xié)英文字母和空格的字符
std::string str2 ("look for non-alphabetic characters...");
std::size_t found2 = str2.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
if (found2!=std::string::npos)
{
std::cout << "The first non-alphabetic character is " << str2[found2];
std::cout << " at position " << found2 << '\n';
}
return 0;
}find_last_of和find_last_not_of與first基本相同,就不寫例子代碼了。
比較與轉(zhuǎn)換:
類似c語言的字符串比較函數(shù)strcmp函數(shù)一樣,支持字符串比較操作,同時(shí)也類似python、C#語言中的函數(shù)一樣,支持把數(shù)字和字符串轉(zhuǎn)換。有些特性是C++11當(dāng)中才有。
注意編譯器bug:
在MinGW編譯器當(dāng)中如果版本低于3.8,雖然支持c++11但是里面有一個(gè)bug,就是不支持字符串和數(shù)組的轉(zhuǎn)換!要更新MinGW的版本才可以,或者直接使用g++。
compare函數(shù):
和strcmp函數(shù)一樣,如果兩個(gè)字符串相等,那么返回0,調(diào)用對(duì)象大于參數(shù)返回1,小于返回-1。
在compare當(dāng)中還支持部分比較,里面有6個(gè)參數(shù)可以設(shè)置。
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string s1="123",s2="123";
cout<<s1.compare(s2)<<endl;//0
s1="123",s2="1234";
cout<<s1.compare(s2)<<endl;//-1
s1="1234",s2="123";
cout<<s1.compare(s2)<<endl;//1
std::string str1 ("green apple");
std::string str2 ("red apple");
if (str1.compare(str2) != 0)
std::cout << str1 << " is not " << str2 << '\n';
//str1的第6個(gè)字符以及后面的4個(gè)字符和參數(shù)比較
if (str1.compare(6,5,"apple") == 0)
std::cout << "still, " << str1 << " is an apple\n";
if (str2.compare(str2.size()-5,5,"apple") == 0)
std::cout << "and " << str2 << " is also an apple\n";
//str1的第6個(gè)字符以及后面的4個(gè)字符和str2的第4個(gè)字符以及后面的4個(gè)字符比較
if (str1.compare(6,5,str2,4,5) == 0)
std::cout << "therefore, both are apples\n";
return 0;
}由于string重載了運(yùn)算符,可以直接用>,<,==來進(jìn)行比較,也很方便。
數(shù)值轉(zhuǎn)換:
在io的部分有過數(shù)值和字符串相互轉(zhuǎn)換的例子,使用的是stringstream函數(shù),在c++11當(dāng)中有定義好的現(xiàn)成的函數(shù)取調(diào)用,非常方便。
| string和數(shù)值轉(zhuǎn)換 | |
|---|---|
| to_string(val) | 把val轉(zhuǎn)換成string |
| stoi(s,p,b) | 把字符串s從p開始轉(zhuǎn)換成b進(jìn)制的int |
| stol(s,p,b) | long |
| stoul(s,p,b) | unsigned long |
| stoll(s,p,b) | long long |
| stoull(s,p,b) | unsigned long long |
| stof(s,p) | float |
| stod(s,p) | double |
| stold(s,p) | long double |
//注意,下段代碼在MinGw中會(huì)報(bào)錯(cuò)!即使使用c++11編譯也一樣,無法識(shí)別to_string!
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string s1;
s1=to_string(100);
cout<<s1<<endl;
int a=stoi(s1,0,10)+1;
cout<<a<<endl;
return 0;
}關(guān)于string如何在C++中使用問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站chinadenli.net,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
標(biāo)題名稱:string如何在C++中使用-創(chuàng)新互聯(lián)
網(wǎng)站路徑:http://chinadenli.net/article46/dgpceg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、云服務(wù)器、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站改版、網(wǎng)站策劃、品牌網(wǎng)站設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容