![](/img/trans.png)
[英]split a string using multiple delimiters (including delimiters) in c++
[英]C++ Extracting the integer in a string with multiple delimiters
我正在嘗試從字符串中提取整數。 這有什么問題嗎? 我只有第一個價值。 我如何才能使它即使在字符串為零的情況下也能正常工作?
string str="91,43,3,23,0;6,9,0-4,29,24";
std::stringstream ss(str);
int x;
while(ss >> x)
{
cout<<"GOT->"<<x<<endl;
char c;
ss >> c; //Discard a non space char.
if(c != ',' || c != '-' || c != ';')
{
ss.unget();
}
}
仔細觀察這一行:
if(c != ',' || c != '-' || c != ';')
請注意,此條件始終為真,因此您始終會unget
標點符號。 然后,當需要數字時,下一次讀取將始終失敗,因為它將讀取標點符號。 更改||
到&&
的應該可以解決此問題。
當然,您的代碼假定str
以非常特殊的方式格式化,並且在給定格式不同的str
值時可能會中斷。 請注意。
您可以通過升壓拆分完成此任務。
int main() {
std::stringstream ss;
std::string inputString = "91,43,3,23,0;6,9,0-4,29,24";
std::string delimiters("|,:-;");
std::vector<std::string> parts;
boost::split(parts, inputString, boost::is_any_of(delimiters));
for(int i = 0; i<parts.size();i++ ) {
std::cout <<parts[i] << " ";
}
return 0;
}
輸出(僅整數):-91 43 3 23 0 6 9 0 4 29 24
這會將字符串更改為char並注銷:,;; -
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "91,43,3,23,0;6,9,0-4,29,24";
str.c_str(); // ex: string a; --> char a[];
char a[99];
int j = 0;
int x;
for(int i = 0; i < str.length(); i++){
if (str[i]!=',' && str[i]!=';' && str[i]!='-'){
a[j] = str[i];
j++;
}
}
return 0;
}
希望這會幫助你。
這適合我的目的,在其中我可以提取整數並在必要時添加定界符。 同樣適用於不同格式的字符串。 (我沒有boost lib,因此更喜歡這種方法。)
int main()
{
string str="2,3,4;0,1,3-4,289,24,21,45;2";
//string str=";2;0,1,3-4,289,24;21,45;2"; //input2
std::stringstream ss(str);
int x=0;
if( str.length() != 0 )
{
while( !ss.eof() )
{
if( ss.peek()!= ',' && ss.peek()!=';' && ss.peek()!='-') /*Delimiters*/
{
ss>>x;
cout<<"val="<<x<<endl;
/* TODO:store integers do processing */
}
ss.get();
}
}
}
您也可以嘗試:
vector<int> SplitNumbersFromString(const string& input, const vector<char>& delimiters)
{
string buff{""};
vector<int> output;
for (auto n : input)
{
if (none_of(delimiters.begin(), delimiters.end(), [n](const char& c){ return c == n; }))
{
buff += n;
}
else
{
if (buff != "")
{
output.push_back(stoi(buff));
buff = "";
}
}
}
if (buff != "") output.push_back(stoi(buff));
return output;
}
vector<char> delimiters = { ',', '-', ';' };
vector<int> numbers = SplitNumbersFromString("91,43,3,23,0;6,9,0-4,29,24", delimiters);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.