如何从C++中的字符串中删除以某个字符开头的所有单词

问题描述 投票:0回答:3

我必须在 C++ 中创建一个函数,该函数将从字符串中删除以用户输入的某个字符开头的所有单词。例如,如果我有一个字符串 “She 决定早上与他见面” 和一个子字符串 “m”,我会得到一个结果字符串 “She up her to up with他在”。 我相信我需要找到 “m” 的出现,删除它及其后面的所有字符,直到空格“”。这是正确的方法吗?如果是,在这种情况下最好使用什么方法?

c++ string substring stringstream
3个回答
3
投票

这里有一个提示。我猜这是一个家庭作业问题。而且我可能放弃了太多。


std::string GetNextWord(const std::string &s, size_t pos)
{
   std::string word;

   // your code goes here to return a string that includes all the chars starting from s[pos] until the start of the next word (including trailing whitespace)

   // return an empty string if at the end of the string
   return word;
}

std::string StripWordsThatBeginWithLetter(const std::string& s, char c)
{
    std::string result;
    std::string word;
    size_t pos = 0;

    while (true)
    {
        word = GetNextWord(s, pos);
        pos += word.size();
        if (word.size() == 0)
        {
            break;
        }
       
        // your code on processing "word" goes here with respect
        // to "c" goes here
    }

    return result;
}

1
投票

法语的简单例子。您是一位优雅的绅士,不想经常说“merde”。这非常困难,所以你决定不说任何以“m”开头的单词。 这个程序将帮助你:

“merde je suis beau merde je le sais”变成“je suis beau je le sais”

#include <string>
#include <algorithm>
#include <iostream>
int main () {
  std::string str ("merde je suis beau merde je le sais");
  const auto forbidden_start ('m');
  std::cout << "initial rude string (words starting with \'" << forbidden_start << "\" : \"" << str << "\"" << std::endl;
  auto i (str.begin ());
  auto wait ((int) 0);
  std::for_each (str.begin (), str.end (), [&i, &forbidden_start, &wait] (const auto& c) {
    if (wait) {
      if (c == ' ') --wait;
    }
    else {
      if (c == forbidden_start) ++wait;
      else *i++ = c;
    }
  });
  if (i != str.end ()) str.erase (i, str.end ());
  std::cout << "\tpolite string : \"" << str << "\"" << std::endl;
}

全部未测试(分隔符为“”),但这就是想法


0
投票

我需要了解的是

stringstream
>>
是如何工作的。感谢大家的帮助!这是代码。

void deleteWordsStartingWithChar(string& str, char c) {
    istringstream ss(str);
    ostringstream oss;
    std::string word;    
    while (ss >> word) {
        if (word[0] == c) {
            continue;
        }
        oss << word << " ";
    }

    str = oss.str();
}
© www.soinside.com 2019 - 2024. All rights reserved.