C++ 如何在给定范围内搜索字符串?

C++ 如何在给定范围内搜索字符串?,c++,string,stl,C++,String,Stl,我必须在指定范围内搜索字符串以查找特定字符。我制定的代码如下: str.erase(str.begin(), str.begin()+5); str.erase(str.begin() + 9, str.end()); // The range to be searched has been specified ie 5th index to 9th index if( str.find('a') != string::npos){ cout << "YES, it

我必须在指定范围内搜索字符串以查找特定字符。我制定的代码如下:

str.erase(str.begin(), str.begin()+5);
str.erase(str.begin() + 9, str.end()); // The range to be searched has been specified ie 5th index to 9th index
 if(  str.find('a') != string::npos){
       cout << "YES, it exists" << endl;
   }else{
       cout << "No, it doesnt" << endl;
   }
str.erase(str.begin(),str.begin()+5);
str.erase(str.begin()+9,str.end());//已指定要搜索的范围,即从第5个索引到第9个索引
if(str.find('a')!=string::npos){
库特
…但我想知道是否有一个标准的库函数可以完成这项工作。(可能在一行中)

您可以使用在不更改原始字符串变量的情况下执行此操作:

if(std::find(std::begin(str) + 5, std::end(str) - 9,'a') != std::end(str) - 9){
   cout << "YES, it exists" << endl;
}else{
   cout << "No, it doesnt" << endl;
}
if(std::find(std::begin(str)+5,std::end(str)-9,'a')!=std::end(str)-9){

你能从字符串中删除字符吗?“/”是什么意思?要搜索的范围已经指定了?代码运行得很好,但我想知道是否有更好的代码(或STL)这样做。@AdithyaDsilva我不知道。您特别想改进什么?我想知道是否有类似str.find(5,9)的代码其中给出了索引值,即在索引5处开始搜索,在索引处结束搜索9@AdithyaDsilva不,在
std::string
中没有这样的函数可用。编写类似于
bool find\u range(const std::string&,size\t start,size\t end,char)的内联函数应该相当容易
if()
语句中的内容。