كيفية تحليل السلسلة المعقدة مع C ++؟
سؤال
أحاول معرفة كيف يمكنني تحليل هذه السلسلة باستخدام "sstream
"و C ++
تنسيقه هو: "سلسلة ، int ، int".
يجب أن أكون قادرًا على تعيين الجزء الأول من السلسلة الذي يحتوي على عنوان IP إلى Std :: String.
فيما يلي مثال على هذه السلسلة:
std::string("127.0.0.1,12,324");
سأحتاج بعد ذلك إلى الحصول عليها
string someString = "127.0.0.1";
int aNumber = 12;
int bNumber = 324;
سأذكر مرة أخرى أنه لا يمكنني استخدام boost
مكتبة ، فقط sstream
:-)
شكرًا
المحلول
إليك وظيفة رمزية مفيدة. لا يستخدم التدفقات ، ولكن يمكنه بسهولة تنفيذ المهمة التي تحتاجها عن طريق تقسيم السلسلة على الفواصل. ثم يمكنك أن تفعل ما تريد مع المتجه الناتج من الرموز.
/// String tokenizer.
///
/// A simple tokenizer - extracts a vector of tokens from a
/// string, delimited by any character in delims.
///
vector<string> tokenize(const string& str, const string& delims)
{
string::size_type start_index, end_index;
vector<string> ret;
// Skip leading delimiters, to get to the first token
start_index = str.find_first_not_of(delims);
// While found a beginning of a new token
//
while (start_index != string::npos)
{
// Find the end of this token
end_index = str.find_first_of(delims, start_index);
// If this is the end of the string
if (end_index == string::npos)
end_index = str.length();
ret.push_back(str.substr(start_index, end_index - start_index));
// Find beginning of the next token
start_index = str.find_first_not_of(delims, end_index);
}
return ret;
}
نصائح أخرى
ال مكتبة مجموعة أدوات C ++ String (Strtk) لديه الحل التالي لمشكلتك:
int main() { std::string data("127.0.0.1,12,324"); string someString; int aNumber; int bNumber; strtk::parse(data,",",someString,aNumber,bNumber); return 0; }
يمكن العثور على المزيد من الأمثلة هنا
إنه ليس خياليًا ولكن يمكنك استخدام std :: getline لتقسيم السلسلة:
std::string example("127.0.0.1,12,324");
std::string temp;
std::vector<std::string> tokens;
std::istringstream buffer(example);
while (std::getline(buffer, temp, ','))
{
tokens.push_back(temp);
}
ثم يمكنك استخراج المعلومات اللازمة من كل من السلاسل المنفصلة.
يمكنك أن تفعل شيئًا كهذا أيضًا ، كما أؤمن (بعيدًا تمامًا عن رأسي ، لذا أعتذر إذا ارتكبت بعض الأخطاء هناك) ...
stringstream myStringStream( "127.0.0.1,12,324" );
int ipa, ipb, ipc, ipd;
char ch;
int aNumber;
int bNumber;
myStringStream >> ipa >> ch >> ipb >> ch >> ipc >> ch >> ipd >> ch >> aNumber >> ch >> bNumber;
stringstream someStringStream;
someStringStream << ipa << "." << ipb << "." << ipc << "." << ipd;
string someString( someStringStream.str() );