C++ 拆分整数值字符串

c++ split int value string

本文关键字:字符串 整数 拆分 C++      更新时间:2023-10-16

我正在尝试用几种不同的方式拆分特定的字符串。我的输入示例是(-5,3,0,1,-2) .

这是我的第一个代码,

// code 1
string s = "(-5,3,0,1,-2)";
int j = 0;
int * temp = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
    if (s[i] != '(' && s[i] != ',' && s[i] != ')') {
        temp[j++] = (s[i]-'0');
    }
}

代码 1 运行良好,除了,它将-符号转换为 ASCII 值 (45( 而不是负整数值。

//code2
char *first = _strdup(s.c_str());
char * temp2 = NULL;
char *temp = strtok_s(first, "(,)", &temp2);
/* Expected output is
temp[0] = -5
temp[1] = 3
temp[2] = 0
temp[3] = 1
temp[4] = -2
*/
但是,在

调试过程中,temp包含 ascii 值,而不是字符串值。也不确定code2是否正常工作。

提前感谢!

你需要一个正确的字符串来转换int。使用 std::stoi。我使用了增强分词器。这对您的情况非常方便。

#include <string>
#include <boost/tokenizer.hpp>
#include <vector>
using namespace std;
using namespace boost;
int main() {
    vector<int> intList
    string text = "(-5,3,0,1,-2)";
    char_separator<char> sep(",");
    tokenizer<char_separator<char>> tokens(text, sep);
    for (const auto& t : tokens) 
          intList.push_back(std::stoi(t));
}

PS.您忘记了删除新内容。请使用适当的容器(例如 std::vector(。

使用 istrstream::get 方法。 您可以通过替换左大括号和右大括号来避免它们。

void _parse_(istrstream &str,string &strText, char ch = ',')
{
    char chText[MAX_PATH];
    str.get(chText, MAX_PATH,ch);
    str.get(ch);
    strText = chText;
}
string s = "(-5,3,0,1,-2)";
istrstream inputStream(s);
string sTemp;
//Replace here the open and close braces.
do
{
   _parse_(inputStream, sTemp,',');
   //Your value in sTemp
}while(!sTemp.empty())

如果需要在没有任何库的情况下使用 c++,则可以使用流代码:

#include <string>
#include <vector>
using namespace std;
int main()
{
    string s = "(-5 2,3 0 1, 0 , 1 , -21 0 )";
    int location = 0;
    vector<int> array;
    string sub;
    while (location <= s.length())
    {
        if ((s[location] >= 48 && s[location] <= 57) || s[location] == 45 || s[location] == 32)
        {
            if (s[location] != 32)
            {
                sub += s[location];
            }
        }
        else
        {
            if (sub.length() != 0)
            {
                std::string::size_type sz;
                int num = stoi(sub, &sz);
                array.push_back(num);
            }
            sub.clear();
        }
        location++;
    }
    return 0;
}
#include <sstream>
#include <iomanip>
using namespace std;
const string INTEGER_CHARS {"0123456789+-"};
vector<int> readIntFromString(const string src) {
    const char stopFlag{''};
    const string str {src + stopFlag};
    vector<int> numbers;
    stringstream ss(str);
    int tmp;
    for(char nextChar = ss.peek(); nextChar != stopFlag; nextChar = ss.peek()) {
        if (INTEGER_CHARS.find(nextChar) != string::npos) {
            ss >> setbase(0) >> tmp;
            numbers.push_back(tmp);
        } else {
            ss.ignore();
        }
    }
    return numbers;
}

setbase(0):使>>运算符识别其他基数,例如 0b010700xF

ss.ignore():跳过我们不在乎的字符

您可以使用

以下内容,

string s = "(-5,3,0,1,-2)";
int j = 0;
string temp;
std::vector<int> values;
for (int i = 0; i < s.length(); i++) 
{
    if (s[i] != '(' && s[i] != ')') 
    {
        while (s[i] != ',' && s[i] != ')')
        {
            temp += s[i];
            ++i;
        }
        values.push_back(std::atoi(temp.c_str()));
        temp.clear();
    }
}