[英]Split a string of positive/negative integers by space
我有以下字符串:
1 -2 -8 4 51
我想得到一個包含5個元素的向量,每個元素對應於字符串中的5個數字。 基本上,我想用空格將上述字符串分隔為定界符。
我在Stack Overflow上發現了很多類似的問題,但是到目前為止,它們中的任何一個都無法獲得第一個“ 1”或最后一個(來自51
)。 我的代碼如下:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
std::vector<std::string> split(std::string str)
{
std::string buf;
std::stringstream ss(str);
vector<std::string> tokens;
while (ss >> buf)
tokens.push_back(buf);
return tokens;
}
int main()
{
std::string temps = "1 -2 -8 4 51";
std::vector<std::string> x = split(temps);
for (int j = 0; j < x.size(); j++){
cout << x[j] << endl;
}
}
我的輸出如下:
-2
-8
4
5
如您所見,第一個和最后一個1被跳過。 我對C ++還是很陌生(我可能已經習慣了其他語言的內置函數.split()
,但是我在上面的代碼中看不到任何錯誤。 誰能幫我了解我在做什么錯?
您顯示的代碼通常可以正常工作。 輸出符合預期,因此問題必須出在顯示的代碼之外。
但是,請注意, vector
將包含std::string
值,而不是int
值。 另外,您應該考慮使用std::istringstream
作為輸入,而不是使用std::stringstream
。
如果您想要一個整數向量,請嘗試以下方法:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
std::vector<int> split(const std::string &str)
{
int num;
std::istringstream iss(str);
std::vector<int> tokens;
while (iss >> num)
tokens.push_back(num);
return tokens;
}
int main()
{
std::string temps = "1 -2 -8 4 51";
std::vector<int> x = split(temps);
for (int j = 0; j < x.size(); j++) {
std::cout << x[j] << std::endl;
}
return 0;
}
然后,您可以使split()
使用std::istream_iterator
和std::back_inserter
代替手動循環,例如:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
#include <algorithm>
std::vector<int> split(const std::string &str)
{
std::istringstream iss(str);
std::vector<int> tokens;
std::copy(
std::istream_iterator<int>(iss),
std::istream_iterator<int>(),
std::back_inserter(tokens)
);
return tokens;
}
int main()
{
std::string temps = "1 -2 -8 4 51";
std::vector<int> x = split(temps);
for (int j = 0; j < x.size(); j++) {
std::cout << x[j] << std::endl;
}
return 0;
}
然后您可以將`split()作為模板函數,以便它可以根據輸入字符串的需要返回不同類型的向量,例如:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
#include <algorithm>
template<typename T>
std::vector<T> split(const std::string &str)
{
std::istringstream iss(str);
std::vector<T> tokens;
std::copy(
std::istream_iterator<T>(iss),
std::istream_iterator<T>(),
std::back_inserter(tokens)
);
return tokens;
}
int main()
{
std::string temps = "1 -2 -8 4 51";
std::vector<int> x = split<int>(temps);
for (int j = 0; j < x.size(); j++) {
std::cout << x[j] << std::endl;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.