【问题标题】:How would I use the following in c++...int searchChar(char, string) [closed]我将如何在 C++ 中使用以下内容...int searchChar(char, string) [关闭]
【发布时间】:2018-09-01 14:04:27
【问题描述】:

我有一个函数定义

int searchChar(char, string)
{/* ... */}

我不知道如何使用它。我必须返回字符在字符串中出现的次数。我认为我们应该将 char 和 string 与变量一起使用。这种方式我不知道怎么用。

【问题讨论】:

  • 那不是函数定义
  • 好的,谢谢这是我的教授让我使用的,我认为这是规范,在 c++ 中。

标签: c++ string function char


【解决方案1】:
#include <iostream>
#include <string>

int searchChar(char /*toFind*/, std::string /*str*/);

int main()
{
    std::string s = "hello world";
    std::cout << searchChar('l', s); // displays '3'
    return 0;
}

int searchChar(char toFind, std::string str)
{
    int count = 0;
    for(size_t i = 0; i < str.length(); ++i)
    {
        if (str[i] == toFind)
            ++count;
    }
    return count;
}

/*
Alternatively:

int searchChar(char toFind, std::string str)
{
    int count = 0;
    for(std::string::iterator iter = str.begin(); iter != str.end(); ++iter)
    {
        if (*iter == toFind)
            ++count;
    }
    return count;
}
*/

/*
Alternatively:

int searchChar(char toFind, std::string str)
{
    int count = 0;
    for(char ch : str)
    {
        if (ch == toFind)
            ++count;
    }
    return count;
}
*/

/*
Alternatively:

#include <algorithm>

int searchChar(char toFind, std::string str)
{
    return std::count(str.begin(), str.end(), toFind);
}
*/

【讨论】:

  • 这本来可以,但是要求使用没有变量名的“char”和“string”。这对我来说很奇怪。但我必须使用“int searchChar(char, string)”
  • 你可以在函数声明中省略参数名称,但你不应该在函数定义中省略它们(因为它需要引用它们,否则没有它们没有意义)。
  • 或者,你的意思是你甚至不能在调用searchChar()的代码中使用变量? cout &lt;&lt; searchChar('l', "hello world");
  • 我必须从 main 中获取一个字符串并使用函数“int searchChar(char, string)”,然后使用 searchChar() 从 main 中搜索该字符串中的字母。
  • 这正是我给你的代码所做的。我认为您误解了您的要求。
猜你喜欢
  • 2011-03-31
  • 2015-08-12
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
相关资源
最近更新 更多