如何将C ++中的字符串标记为子字符串

时间:2014-05-09 07:11:05

标签: c++ string

我有:

string content;

由用户输入。

例如:

content = "I am new to this site".

我想遍历这个字符串,对于句子中的每个单词,我想运行一个处理单词的函数。

类似的东西:

for(int i = 0; i < stringSize; i++){
//remove a word from the string
process(word);
}

非常感谢任何帮助。谢谢

3 个答案:

答案 0 :(得分:1)

如果您可以使用以下内容,请在空格(空格,制表符,换行符等)上拆分std::string

std::string content = "I am new to this site";
std::vector<std::string> words;  // Will contain each word of the `content` string

std::istringstream iss(content);
std::copy(std::istream_iterator<std::string>(iss),
          std::istream_iterator<std::string>(),
          std::back_inserter(words));

for (const std::string& w : words)
    std::cout << w << '\n';

以上代码段会打印出content中的每个字,每行一个字。

参考文献:

答案 1 :(得分:0)

这是一个接受字符串并返回标记列表的函数。

std::vector<std::string> tokenize(std::string const& content)
{
   std::vector<std::string> tokens;
   size_t iter = 0;
   size_t next = 0;
   while ( ( next = content.find(" ", iter)) != std::string::npos )
   {
      tokens.push_back(content.substr(iter, next-iter));
      iter = ++next;
   }
   tokens.push_back(content.substr(iter));
   return tokens;
}

这是我用来测试它的主要功能。

int main()
{
   std::string content = "I am new to this site";
   std::vector<std::string> tokens = tokenize(content);
   std::vector<std::string>::iterator iter = tokens.begin();
   for ( ; iter != tokens.end(); ++iter )
   {
      std::cout << *iter << std::endl;
   }
}

这是输出:

I
am
new
to
this
site

答案 2 :(得分:0)

这是一个提升解决方案,只是为了它的乐趣。它将删除您不想要的字符串,并将连续的分隔符视为一个。如果您没有C ++ 11,请将lambda替换为指向您自己函数的指针:

#include <boost/algorithm/string/find_iterator.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;

int main(int argc, char** argv) 
{
    const string delim{' '};
    vector<string> splitVec;
    string inStr = "keep all this but remove THAT if you see it";
    boost::split( splitVec, inStr, boost::algorithm::is_any_of(&delim[0]), boost::token_compress_on );
    copy_if(splitVec.begin(),splitVec.end(), ostream_iterator<string>(cout," "), [](const string& argStr) -> bool { return(argStr != "THAT"); } );
}

给出:

keep all this but remove if you see it