c++ - 当 substring 只是一个换行符时,string.find(substring) 函数返回什么?

标签 c++ string

我有一个程序,用于检查字符串中的子字符串。 程序:

#include<iostream>
#include<cstring>
int main()
{
  std::string str, substr;
  std::cout<<"\n Enter a string : ";
  std::getline(std::cin, str);
  std::cout<<"\n Enter a possible substring of the string : ";
  std::getline(std::cin, substr);
  std::size_t position = str.find(substr);
  if(position != std::string::npos)
    std::cout<<substr<<" was found at position "<<position<<std::endl;
  else
    std::cout<<"\n The substring you entered wasn't found \n";
  return 0;
}

我有一个输入没有给出正确的输出。 示例:

 Enter a string : Stackoverflow         

 Enter a possible substring of the string : 
 was found at position 0

在输入子字符串时,我只需按回车键。所以输出应该是 The substring you entered was not found。 在这种情况下,find() 方法返回什么?

最佳答案

在空输入上按回车键不会在字符串中放入换行符。 std::getline消耗换行符,所以你所有的子字符串都是空字符串。

根据 cppreference函数std::string::find

an empty substring is found at pos if and only if pos <= size()

在你的例子中 pos0因为你使用默认参数所以find返回 0 .自 find返回 0你满足if条件。为防止这种情况,您可以检查一个空字符串,如

if(position != std::string::npos && !substr.empty())

关于c++ - 当 substring 只是一个换行符时,string.find(substring) 函数返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35363906/

相关文章:

c++ - Eclipse CDT/GDB 错误 : Undefined maintenance set command: "python print-stack off". 尝试 "help maintenance set"

c++ - 对指针 C++ 的参数引用

javascript - 我可以在 jQuery .text() 上使用 Javascript 字符串对象方法吗

ruby-on-rails - 使用 String#split 方法

java - 字符串是第二个的子串?

c - 尝试删除字符串字符

c++ - std::vector 如何调整其内部缓冲区的大小?

c++ - 了解复制对象

c++ - 比较运算符

javascript string exec奇怪的行为