c++ - 给出字符串值列表

标签 c++ string std

std::string text;
std::getline(std::cin, text);

根据以上设置,我如何识别将在文本中输入的字符串列表是否等于单个值?

例如:

std::string text;
std::getline(std::cin, text);
std::string aux; //Added
text.find("word ", "thisword", "another", "floor") = aux; //Added

if(text.find("lutece labs" + aux) != std::string::npos); //Goal
{
...megh...
}

我觉得上面的代码有点乱七八糟,但我希望它能解释我要找的东西。所有字符串输入都来自文本。那么我怎样才能制作一个可以在文本中找到的单词列表,这样我就可以使新列表等于一个值呢?希望我问清楚了。谢谢!

最佳答案

你可以有类似下面的东西,可能不是最好的方法:

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

int main()
{
        std::string text = "This is a long text word \
                            this word another floor king \
                            queen ace";

    std::stringstream ss(text) ; 

    std::vector<std::string> vec{ // Form a vector of string
                std::istream_iterator<std::string>(ss),
                std::istream_iterator<std::string>() };

    // Get list of words to be searched for
    std::vector<std::string> to_find {"word ", "this", 
                          "word", "another", "floor"};                   

    std::string aux ="jack"; // the replace word

    std::replace_if(   vec.begin( ),vec.end( ), /* Loop over vec */
                    [to_find](const std::string& x)
                    {  /* Find if any from to_find is present */
                       return std::any_of( 
                              to_find.begin(), 
                              to_find.end(),
                              [x](const std::string& y)
                              { return x == y; }
                                         ) ;
                    },
                    aux );

    /* Now get your modified text */                
    text =std::accumulate( vec.begin()+1, vec.end( ), 
                           vec[0],
                         [](std::string s0, std::string const& s1) 
                         { return s0 += " " + s1; }
                        );
    std::cout << text ;

}

参见 Here (只是一个简单的demo,需要检查边界条件)

关于c++ - 给出字符串值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25144404/

相关文章:

c++ - C++阻止刷新

c++ - 潜在的 g++ 模板错误?

android - 如何按字符串删除 sqlite 表行条目?

c++ - 如何让 wstring_convert::to_bytes 抛出 range_error 异常?

c++ - Mac 上体系结构 x86_64 c++ 的 undefined symbol

c++ - 静态断言实例化时模板类型的大小

c++ - 在 2 个 cpp 文件中定义一个 C++ 类?

c# - 将指数数字符串表示形式拆分为幂和指数

java - java中以字符开头并后跟数字的子字符串

c - 如何在掷骰子时成功地在 C 语言中使用 rand,而无需花费 1000 秒的时间才能获得正确的结果?