std::string text;
std::getline(std::cin, text);
使用上面的设置,如何识别字符串列表,这些字符串将在文本中输入,等于单个值?
EX:
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...
}
我觉得我宰了上面的代码,但我希望它能解释我在寻找什么。所有字符串输入都来自文本。那么我怎样才能列出可以在文本中找到的单词列表,这样我可以使新列表等于一个值?希望我清楚地问清楚。谢谢!
答案 0 :(得分:1)
您可以拥有以下内容,可能不是最佳方法:
#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(只是一个简单的演示,您需要检查边界条件)
答案 1 :(得分:0)
尝试以下方法:
#include <algorithm>
#include <string>
#include <iostream>
namespace detail
{
template<int... Is>
struct index_sequence { };
template<int N, int... Is>
struct make_index_sequence : make_index_sequence<N-1, N-1, Is...> { };
template<int... Is>
struct make_index_sequence<0, Is...> : index_sequence<Is...> { };
void replace_all_with_t(std::string, std::string)
{
}
template<class... Tail>
void replace_all_with_t(std::string& c,
std::string value,
std::string head, Tail&&...tail)
{
while (c.find(head) != std::string::npos)
c.replace(c.find(head), head.size(), value);
replace_all_with_t(c, std::move(value), std::forward<Tail>(tail)...);
}
template<class Tuple, int... Is>
void replace_all_with(std::string& c,
Tuple&& tokens,
std::string value,
detail::index_sequence<Is...>)
{
replace_all_with_t(c, std::move(value), std::get<Is>(std::forward<Tuple>(tokens))...);
}
}
template<class Tuple>
void replace_all_with(std::string& c,
Tuple&& tokens,
std::string value)
{
detail::replace_all_with(c, std::forward<Tuple>(tokens), std::move(value),
detail::make_index_sequence<std::tuple_size<Tuple>::value>());
}
int main()
{
std::string s = "abchellojsoncrazyabcworldabc";
replace_all_with(s, std::make_tuple("abc", "json"), "*");
std::cout << s;
}