【问题标题】:How to search in a string within a given range?如何在给定范围内搜索字符串?
【发布时间】:2017-10-11 17:57:04
【问题描述】:

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

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;
   }

上面的代码按预期工作,但我很想知道是否有标准库函数可以完成这项工作。(可能在一行中)

【问题讨论】:

  • 您从字符串中删除字符。 “//指定要搜索的范围”是什么意思?

标签: c++ string stl


【解决方案1】:

...但我很想知道是否有一个标准库函数可以完成这项工作。(可能在一行中)

您可以使用std::find() 来执行此操作,而无需更改原始字符串变量:

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;
}

【讨论】:

  • 代码工作得很好,但我想知道是否有更好的代码(或 STL)来做到这一点。
  • @AdithyaDsilva 我不知道。您特别想改进什么?
  • 我想知道是否有像 str.find(5, 9) 这样的代码,其中给出了索引的值,即从索引 5 开始搜索并在索引 9 结束搜索
  • @AdithyaDsilva 不,std::string 没有这样的功能。不过,编写一个看起来像 bool find_range(const std::string&amp;, size_t start, size_t end,char) 的内联函数应该相当容易,以包装我在 if() 语句中放入的内容。
猜你喜欢
  • 2018-02-10
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
相关资源
最近更新 更多