字符串分割C++

 1 int to_int(std::string& strInput)
 2 {
 3     int nReturn = 0;
 4     std::stringstream ss;
 5     ss << strInput;
 6     ss >> nReturn;
 7     return nReturn;
 8 }
 9 int getNumFromString(std::string& strChannelNo, int nIndex)
10 {
11     std::vector<std::string> vResults;
12     int start = 0;
13     int end = strChannelNo.find("_");//待分割的字符串
14     int delimiter_len = 1;//待分割的字符串长度
15 
16     while (end != std::string::npos) {
17         std::string token = strChannelNo.substr(start, end - start);
18         if (!token.empty()) {
19             vResults.push_back(token);
20         }
21         start = end + delimiter_len;
22         end = strChannelNo.find("_", start);
23     }
24 
25     // 添加最后一个子串
26     std::string lastToken = strChannelNo.substr(start);
27     if (!lastToken.empty()) {
28         vResults.push_back(lastToken);
29     }
30     return to_int(vResults[nIndex - 1]);
31 }

 

posted @ 2025-06-17 15:27  冥天笑  阅读(11)  评论(0)    收藏  举报