如何在C ++中将字符串拆分为字符串数组,而不进行单词拆分

时间:2016-02-17 13:33:28

标签: c++ arrays string

我需要将输入字符串(空格分隔的单词数组)拆分为最大长度为M的字符串数组,而不会破坏任何单词。如何在C ++中做到这一点?

例如:

std::string inputStr = "I need to split input string";
unsigned M = 10;
// split M characters by M characters
std::vector<std::string> output = split_string(inputStr, " ", M); 
//output contains {"I need to ","split ","input ","string"} 

3 个答案:

答案 0 :(得分:0)

using namespace std;

char str[] = "I need to split input string";
int M=10;

vector<string> data;
string part;

char* p = strtok(str, " ");
while (p != NULL) {
  string buf = part + string(p);
  if(buf.length() > M && !part.empty()) {
    data.push_back(part);
    part.clear();
  }
  part = string(p);
  p = strtok(NULL, " ");
}
if(!part.empty()) {
  data.push_back(part);
}

答案 1 :(得分:0)

这段代码可以准确地给出你想要的输出,但它不仅仅是&#34;用空格分割&#34;。

http://ideone.com/mrIvLV

std::string str = "I need to split input string";   
std::vector<std::string> output;

std::istringstream iss(str);
std::string word;
const int max = 10;

while((iss >> word))
{   
    // Check if the last element can still hold another word (+ space)
    if (output.size() > 0 && (output[output.size() - 1].size() + word.size() + 1) <= max)
        output[output.size() - 1] += ' ' + word;
    else        
        output.push_back(word);
}

答案 2 :(得分:0)

std::vector<std::string> split_string(const std::string &str, const std::string delim = " ", size_t pos = 0)
{
  std::vector<std::string> out;
  if (pos >= str.size())
    return out;

  size_t currentPos = 0;
  while (str.find(delim, pos + 1) != std::string::npos){
    out.push_back(str.substr(currentPos, str.find(delim, pos + 1)-currentPos));
    pos = str.find(delim, pos + 1);
    currentPos = pos;
  }
  out.push_back(str.substr(pos));

  return out;
}