在讀取配置文件的每行內(nèi)容的時(shí)候,需要去掉字符串中的空格或則tab鍵,
在C里實(shí)現(xiàn)它還是比較容易,但要是用string類來存儲(chǔ)每行字符串的時(shí)候,
可能就不會(huì)象C那樣容易處理字符串的每個(gè)字符。
為了處理方便,利用遞歸來去掉string的所有空格字符:
對(duì)整體程序有明顯的降低。
如果只是去除兩端的空格字符則比較簡(jiǎn)單一些,網(wǎng)絡(luò)到處都有它相關(guān)的例子:
在C里實(shí)現(xiàn)它還是比較容易,但要是用string類來存儲(chǔ)每行字符串的時(shí)候,
可能就不會(huì)象C那樣容易處理字符串的每個(gè)字符。
為了處理方便,利用遞歸來去掉string的所有空格字符:
1
string& trim(string &str, string::size_type pos = 0)
2

{
3
static const string delim = " \t"; //刪除空格或者tab字符
4
pos = str.find_first_of(delim, pos);
5
if (pos == string::npos)
6
return str;
7
return trim(str.erase(pos, 1));
8
}
因?yàn)榕渲梦募锩啃械膬?nèi)容不會(huì)很多,使用遞歸來講可能也不會(huì)
2



3

4

5

6

7

8

對(duì)整體程序有明顯的降低。
如果只是去除兩端的空格字符則比較簡(jiǎn)單一些,網(wǎng)絡(luò)到處都有它相關(guān)的例子:
1
string trimEnd(string &str)
2

{
3
const string &delim =" \t" ;
4
string r=str.erase(str.find_last_not_of(delim)+1);
5
return r.erase(0,r.find_first_not_of(delim));
6
}

2



3

4

5

6
