【问题标题】:Removing all occurrences of a character from a string in C++从 C++ 中的字符串中删除所有出现的字符
【发布时间】:2020-08-04 13:14:28
【问题描述】:

我的任务说我应该编写一个名为 removeChar 的函数;

  1. 接受 4 个输入:一个整数 num、一个字符串 str、一个字符串 s 和一个字符 c,但不返回 任何东西。

  2. 查找 s 中出现的所有 c 的数量(大写和小写)(提示:您可以 使用ASCII码进行比较))并保存在num中

  3. 将修剪后的字符串复制到str中

  4. 在同一个文件中编写一个 main() 函数,其中包含一系列测试以展示正确的 removeChar() 的行为。

但是所有的打印操作都应该在 main() 函数中完成。我有这个代码:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string removeChar(int num, string s, string str, char c);
int main()
{
    string s = "asdfasdf";
    s = removeChar(1, "a", "hello", 'h');
    cout << s;
}
string removeChar(int num, string s, string str, char c)
{
    int i;
    for (i = 0; i < s.length(); i++)
        if (int(s.at(i)) == int(c))
            num = int(c);
    str.erase(std::remove(str.begin(), str.end(), (char)num), str.end());
    return str;
}

它不起作用,即使它起作用,我也需要一个void函数。

【问题讨论】:

  • 提示:输出参数必须是引用。
  • @Marque Phoenix 这个函数声明 string removeChar(int num, string s, string str, char c);没有任何意义。例如函数中没有使用参数num。
  • 如果你需要一个不返回任何东西的函数,那么结果也需要是一个参数(引用)。
  • s中查找c的所有出现次数可能意味着“cs中出现了多少次”,而不是“字符@的数值是多少987654326@"
  • 在要求 3 上,“修剪后的字符串”是什么?

标签: c++ string algorithm function char


【解决方案1】:

如果我正确理解了作业的描述, 那么您需要以下内容:

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <cctype>

void removeChar( std::string::size_type &n, std::string &str, const std::string &s, char c )
{
    str.clear();

    c = std::toupper( ( unsigned char )c );

    auto equal_to_c = [&c]( const auto &item )
    {
        return std::toupper( ( unsigned char )item ) == c;
    };

    std::remove_copy_if( std::begin( s ), std::end( s ),
                         std::back_inserter( str ),
                         equal_to_c );

    n = s.size() - str.size();                                   
}

int main() 
{
    std::string::size_type n = 0;
    std::string str;

    removeChar( n, str, "This is a silly assignment", 's' );

    std::cout << "n = " << n << ", str = " << str << '\n';

    return 0;
}

程序输出为:

n = 5, str = Thi i a illy aignment

【讨论】:

  • 很好,现在他在解释解决方案时会遇到比他最初遇到的问题更多的问题:-)
  • 你可以修复字符串“assignment”...“m”太多了。
  • @YesThatIsMyName 谢谢。我删除了多余的字母。
  • @YesThatIsMyName 是的,实际上我什至不知道汽车是什么,但我想我会努力学习的。
猜你喜欢
  • 2014-08-07
  • 2013-12-18
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-02
相关资源
最近更新 更多