【发布时间】:2020-09-16 12:29:30
【问题描述】:
谁能帮我理解为什么这个循环不起作用?我正在尝试做两件事:
- 使用 mystring.length() 遍历字符串
- 在字符串中查找任何 0 或 1
这两个功能都不起作用。例如,如果我传入一个 123450 的字符串,那么 a) 它只循环一次 b) 即使第一个字符是 1,它也会返回 "no, no, no"
bool recognizer(string s)
{
string mystring = s;
for (int i = 0; i < mystring.length(); i++) {
if ((mystring[i] == 0) || (mystring[i] == 1)) {
cout << "yes, yes, yes";
return true;
}
else {
cout << "no,no,no";
return false;
}
}
}// end of recognizer
【问题讨论】:
-
您可能希望使用基于范围的 for 循环。
for (const auto& ch : mystring) { if ( ch == '0' || ch == '1') { // rest of code here -
no,no,no, Daniel San! -
OT:最好通过 const 引用传递字符串参数。
-
复制到
mystring似乎也没有意义... -
但我需要为字符串中的每个字符返回“true”或“false”。如果 bool 函数在第一次返回后终止,我将如何进行多次返回?