在平常做算法題的時(shí)候,經(jīng)常會(huì)碰到遍歷字符串,然后將在將目前遍歷的子串與已經(jīng)遍歷過(guò)的進(jìn)行其他操作時(shí),我們需要將子串由char類型轉(zhuǎn)換為string類型。以下是幾種簡(jiǎn)單的方法。
1、使用賦值 =?
#include <iostream>
#include <string>
unsing namespace std;
int main()
{
char c = 'A';
string s;
s = c;
cout << s << endl;
return 0;
}
切記不能用 string s = c;沒(méi)有這種寫(xiě)法,會(huì)報(bào)錯(cuò)。
2、利用填充構(gòu)造函數(shù) string(size_t n, char c)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-598534.html
char c = 'A';
string s(1, c);
3、string.push_back文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-598534.html
s.push_back(c);
到了這里,關(guān)于char轉(zhuǎn)string的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!