代码之家  ›  专栏  ›  技术社区  ›  Maxpm

将字符串解析为整数数组

  •  2
  • Maxpm  · 技术社区  · 15 年前

    我正在寻找一种方法,将一个带有指定分隔符(如斜线或空格)的字符串转换为一个由这些分隔符分隔的整数数组。

    例如,如果用户输入 12/3/875/256 ,我需要检索数组 {12, 3, 875, 256} . 理想情况下,它可以处理任意长度。

    我试着一个字符一个字符地扫过字符串,并将所有非除法器的内容存储在一个临时变量中,下次遇到除法器字符时,这个临时变量会添加到数组中。不幸的是,类型转换是一个痛苦的屁股。有更简单的方法吗?

    5 回复  |  直到 15 年前
        1
  •  2
  •   Jan Gorzny    15 年前

    可以将“/”设置为分隔符并使用getline读取?然后,您必须将每个变量放入一个变量中,并且您需要知道大小——也许您可以通过数组并计算斜线数?然后你就知道了,可以先设置数组。您可能需要将每个字符串段解析为int,这可能很困难,也可能不困难。(暂时没有使用C++,我不记得一个方便的方法。)

    见 here 举一个小例子来说明这是如何做到的(下发3个帖子)。

        2
  •  1
  •   yasouser    15 年前
        3
  •  1
  •   Community Mohan Dere    9 年前

    斯特托克和斯特托尔?(这有点像在开玩笑。斯特托克通常不是个好主意)

    分裂在这里面 Parsing String to Array of Integers

    C++中的字符串转换为int有很多相关问题。 https://stackoverflow.com/search?q=convert+string+to+int+c%2B%2B

    类型转换有什么问题?据我所见,这似乎不是一个街区。

    你能出示你的密码吗?

        4
  •  1
  •   Community Mohan Dere    9 年前

    看看 this other answer . 它甚至还有一个使用boost::tokenizer的tokenizer代码示例。

    编辑:

    我在那里复制了代码,并做了必要的修改:

    #include <iostream>
    #include <string>
    #include <boost/foreach.hpp>
    #include <boost/tokenizer.hpp>
    #include <vector>
    #include <boost/lexical_cast.hpp>
    #include <iterator>
    #include <algorithm>
    
    using namespace std;
    using namespace boost;
    
    int main(int argc, char** argv)
    {
       string text = "125/55/66";
       vector<int> vi;
    
       char_separator<char> sep("/");
       tokenizer<char_separator<char> > tokens(text, sep);
       BOOST_FOREACH(string t, tokens)
       {
          vi.push_back(lexical_cast<int>(t));
       }
    
       copy(vi.begin(), vi.end(), ostream_iterator<int>(cout, "\n"));
    }
    

    将打印:

    125
    55
    66
    
        5
  •  0
  •   wkl    15 年前

    你可以结合使用 Boost.split 和 Boost.lexical_cast 用您想要的分隔符分解字符串,然后您可以在词汇中对其全部进行强制转换。

    #include <boost/foreach.hpp>
    #include <boost/lexical_cast.hpp>
    #include <boost/algorithm/string.hpp>
    
    
    #include <iostream>
    #include <vector>
    #include <string>
    
    int main()
    {
        std::string s = "11/23/2010";
        std::vector<std::string> svec;
        std::vector<int> ivec;
    
        // split the string 's' on '/' delimiter, and the resulting tokens
        // will be in svec.
        boost::split(svec, s, boost::is_any_of("/"));
    
        // Simple conversion - iterate through the token vector svec
        // and attempt a lexical cast on each string to int
        BOOST_FOREACH(std::string item, svec)
        {
            try
            {
                int i = boost::lexical_cast<int>(item);
                ivec.push_back(i);
            }
            catch (boost::bad_lexical_cast &ex)
            {
                std::cout << ex.what();
            }
        }
    
        return 0;
    }
    

    未经测试…这台机器没有动力。

    其他可以用来转换的方法 std::string / char * 到 int 涉及的类型 stringstream 直接使用,或C结构,如 atoi .