c++的find方法不工作
C++ find method not working
我对c++很陌生,所以我很抱歉缺乏知识,但是由于某种原因,我的find方法不起作用。任何帮助将是伟大的,这是我正在使用的代码。
www.pastie.org/9434690//String s21
string s21 ="| o |";
if(s21.find("1")){
cout << "IT WORKS OMG " << s21 << endl;
}
else if(!s21.find("1")){
cout << "HASOSDKHFSIF" << endl;
}
感谢忘了说,代码总是打印"IT WORKS",即使字符串中没有"o"。
这里的问题是你的if语句。s21.find("1")
将返回要匹配的字符串的字符串中第一个出现的索引。如果没有找到匹配项,则返回string::npos
,这是值-1
的枚举。If语句将对所有不等于零的数字返回true。因此,您需要像这样对string::npos
进行测试:
if(s21.find("1") != std::string::npos)
{
cout << "IT WORKS OMG " << s21 << endl;
}
else
{
cout << "HASOSDKHFSIF" << endl;
}
std::string::find
的返回值是找到的子字符串的第一个字符的位置,如果没有找到这样的子字符串,则 std::string::npos
返回值。
您应该使用 std::string::npos
进行字符串匹配
if(s21.find("1") != std::string::npos )
{
cout << "IT WORKS OMG " << s21 << endl;
}
else
{
cout << "HASOSDKHFSIF" << endl;
}
如果你想聪明一点,std::string::npos
是二进制中最大的unsigned int
,或者1111 1111 1111 1111
(人们有时会将str.find()与int -1进行比较,尽管不建议这样做)。您可以通过一些按位操作来利用这个位模式。
翻转所有的位将为除了std::string::npos
之外的每个位模式提供非零值,并且由于c++将所有非零值视为true
,因此您的if实际上可以是:
if(~s21.find("1"))
{
cout << "IT WORKS OMG " << s21 << endl;
}
else if(!~s21.find("1"))
{
cout << "HASOSDKHFSIF" << endl;
}
相关文章:
- C++ assigment std::list:<typename>:itrator 在 main 中工作,但在方法中它不起作用
- Poco 库 PUT 方法未按预期工作,尽管主机、方法、内容类型设置正确
- std::bind,无法让具有单个参数的方法工作
- 私有变量无法正常工作的C++getter方法(只有Java经验)
- 虚拟基类在内部如何工作?编译器如何解析对基方法的调用?
- 让类与运算符一起工作更简单的方法
- 找不到使保证返回值优化工作的方法
- C++ set_difference方法未按预期工作
- 解决方法:'can not be used when making a shared object; recompile with -fPIC'使用Cmake。使用普通的 g++ 工作
- 尝试使用 Qt 库中的 QPixmap 将图像拆分为多个块。关于他的复制方法的工作方式,我有什么不明白的吗?
- C 方法无法工作
- 我是否应该在构造函数或成员方法中进行大量初始化工作
- 请告诉我在巴泽尔拥有多平台工作空间的更好方法
- 这种奇怪的 I/O 方法是如何工作的?
- 在 Xcode 中工作的 CMake 中启用地址清理器的正确方法是什么
- 在Qt中使用工作线程将数据写入文件的正确方法是什么?
- 我试着了解方法覆盖是如何工作的,不知道为什么输出 2
- 我的重载后增量方法无法按预期工作。为什么?
- 无法使方法存在检测机制正常工作
- 在多线程中使用curl句柄的错误工作方法的替代方法