在字符串中查找所有想要的单词 [英] Finding all wanted words in a string

查看:336
本文介绍了在字符串中查找所有想要的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个太长的字符串,我想找到并找到所有想要的字。例如,我想查找字符串中所有apple的位置。你能告诉我我是怎么做的吗?
感谢

I have a string which is too long, I want to find and locate all of the wanted words. For example I want to find the locations of all "apple"s in the string. Can you tell me how I do that? Thanks

推荐答案

重复申请 std :: string :: find 如果您使用的是C ++字符串或 std :: strstr 使用C字符串;在这两种情况下,在每次迭代开始在最后一次匹配后搜索n个字符,其中n是您的单词的长度。

Apply repeatedly std::string::find if you are using C++ strings, or std::strstr if you are using C strings; in both cases, at each iteration start to search n characters after the last match, where n is the length of your word.

std::string str="one apple two apples three apples";
std::string search="apple";
for(std::string::size_type pos=0; pos<str.size(); pos+=search.size())
{
    pos=str.find(search, pos);
    if(pos==std::string::npos)
        break;
    std::cout<<"Match found at: "<<pos<<std::endl;
}

link

这篇关于在字符串中查找所有想要的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆