下面是更靈活(希望)位的代碼的另一個版本。它發現「(」sing,then「)」用逗號分割它們,去掉所有的空白字符並將數字轉換爲整數。然後它將它們打印出來。
#include <string>
#include <iostream>
using namespace std;
//these three functions are taken from here:
//http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
int main()
{
string s = "std::vector<int>(612,30)";
int paren_start = s.find("(")+1;
string numbers = s.substr(paren_start, s.find(")")-paren_start);
int comma_pos = numbers.find(",");
string first_num = numbers.substr(0, comma_pos);
string second_num = numbers.substr(comma_pos+1, numbers.size()-comma_pos);
int first = atoi(trim(first_num).c_str());
int second = atoi(trim(second_num).c_str());
cout << "{" << endl;
for(int i=0; i<first; i++)
{
cout << second << " ";
}
cout << "}" << endl;
return 0;
}
這可能是矯枉過正,但我敢肯定,[漂亮的打印](http://stackoverflow.com/questions/4850473/pretty-print-c-stl-containers)可以處理它。 – chris 2013-03-18 15:15:46
效率高但不靈活。 – deepmax 2013-03-18 15:15:52
如果您正在尋找更靈活的方式來解析這些內容,您可能需要使用std :: regex或boost :: spirit。正則表達式永不放棄 – 2013-03-18 15:17:22