使用C ++拆分字符串

时间:2013-04-26 18:20:27

标签: c++ string split

我在使用纯C ++分割字符串时遇到问题

字符串总是如下所示

12344//1238

首先是int然后是//然后是第二个int。

需要帮助来获取两个int值并忽略//

6 个答案:

答案 0 :(得分:1)

string org = "12344//1238";

size_t p = org.find("//");
string str2 = org.substr(0,p);
string str3 = org.substr(p+2,org.size());

cout << str2 << " "<< str3;

答案 1 :(得分:1)

为什么我们不能使用sscanf?

char os[20]={"12344//1238"};
int a,b;
sscanf(os,"%d//%d",a,b);

Reference

答案 2 :(得分:0)

查看strtok功能

答案 3 :(得分:0)

这应该拆分并转换为整数:

#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>

class BadConversion : public std::runtime_error {
public:
  BadConversion(std::string const& s)
    : std::runtime_error(s)
    { }
};

inline double convertToInt(std::string const& s,
                              bool failIfLeftoverChars = true)
{
  std::istringstream i(s);
  int x;
  char c;
  if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
    throw BadConversion("convertToInt(\"" + s + "\")");
  return x;
}

int main()
{
    std::string pieces = "12344//1238";

    unsigned pos;
    pos = pieces.find("//");
    std::string first = pieces.substr(0, pos);
    std::string second = pieces.substr(pos + 2);
    std::cout << "first: " << first << " second " << second << std::endl;
    double d1 = convertToInt(first), d2 = convertToInt(second) ;
    std::cout << d1 << " " << d2 << std::endl ;
}

答案 4 :(得分:0)

我能想到的最简单的方式:

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

void main ()
{
 int int1, int2;
 char slash1, slash2;

 //HERE IT IS:
 stringstream os ("12344//1238");
 os>> int1 >> slash1 >> slash2 >> int2;
 //You may want to verify that slash1 and slash2 really are /'s

 cout << "I just read in " << int1 << " and " << int2 << ".\n";

 system ("pause");
}

也很好,因为它很容易重写 - 例如,如果您决定读取由其他内容分隔的整数。

答案 5 :(得分:0)

将整数作为字符串。 然后该字符串将包含数字和//符号。 接下来,您可以运行一个简单的for循环来查找字符串中的'/'。 符号前面的值存储在另一个字符串中。 当'/'出现时,for循环将终止。您现在拥有第一个索引 '/'符号。 增加索引并使用for循环复制其余字符串,在另一个中 串。 现在你有两个单独的字符串。