我被困在設計這個功能:解析兩個或一個號::串
//Turns "[0-9]+,[0-9]+" into two integers. Turns "[0-9]+" in two *equal* integers
static void parseRange(const std::string, int&, int&);
我沒有獲得正則表達式(這需要無論是C++ 11或Boost庫)。我需要以某種方式查明該字符串是否包含2個整數並將其分開,然後獲取每個整數。
我想我需要strstr
版本使用std::string
找出是否有逗號和地方。我可能可以用std::string::c_str
值運作。廣泛的搜索使我這個(但我想用std::string
,不C字符串):
void Generator::parseRange(const std::string str, int& min, int& max) {
const char* cstr = str.c_str();
const char* comma_pos;
//There's a comma
if((comma_pos=strstr(cstr, ","))!=NULL) { //(http://en.cppreference.com/w/cpp/string/byte/strstr)
//The distance between begining of string and the comma???
//Can I do this thing with pointers???
//Is 1 unit of pointer really 1 character???
unsigned int num_len = (comma_pos-cstr);
//Create new C string and copy the first part to it (http://stackoverflow.com/q/8164000/607407)
char* first_number=(char *)malloc((num_len+1)*sizeof(char));//+1 for \0 character
//Make sure it ends with \0
first_number[num_len] = 0;
//Copy the other string to it
memcpy(first_number, cstr, num_len*sizeof(char));
//Use atoi
min = atoi(first_number);
max = atoi(comma_pos+1);
//free memory - thanks @Christophe
free(first_number);
}
//Else just convert string to int. Easy as long as there's no messed up input
else {
min = atoi(cstr); //(http://www.cplusplus.com/reference/cstdlib/atoi/)
max = atoi(cstr);
}
}
我Google了很多。你不能說我沒有嘗試。上面的函數有效,但我更喜歡一些不那麼天真的實現,因爲你上面看到的是來自舊時代的硬核C代碼。這一切都依賴於沒有人因輸入而混淆的事實。
1)在C++中避免malloc()! 2)你內存泄漏 – Christophe 2014-12-08 01:03:19
這就是爲什麼我要求C++解決方案。在學校裏,他們只教我們C,我正在盡我所能,這顯然是我想要的。 – 2014-12-08 01:04:45