首页 > 解决方案 > 如何制作一个接受 std::string 参数的函数,该参数将返回由空格包围的任何内容的数量

问题描述

我想创建一个接受std::string参数并返回其中int单词数量的函数。像这样:

int countWords(std::string){
    // code...
    return amountOfWords;
}

标签: c++string

解决方案


编写一个函数存根:

int stub(const std::string& s/*don't deep copy the string*/)
{
    return function_you_found_online(s.c_str());
}

该函数c_str()将 a 返回const char*到 中的第一个字符s

使用函数存根包装第三方资源还有一个优势,即您可以在以后切换资源,而不会过多地影响您的代码库。


推荐阅读