【发布时间】:2018-10-20 07:04:21
【问题描述】:
假设我们让用户输入一个字符串"william" 的名称,然后用户输入他们想要查找索引的字符。
using namespace std;
string name;
char characterToFind;
cout << "Enter a name ";
cin >> name;
cout << "Enter a character to find ";
cin >> characterToFind;
然后我们想在name字符串数组中找到字符的索引。
for (int j = 0; j < name.length(); j++) {
if (name[j] == characterToFind) {
cout << "char is at index: " << j << endl;
}
}
然后我如何检查输入的字符是否不存在于name 字符串数组中?我尝试执行以下操作:
if (characterToFind != name.find(characterToFind)) {
cout<< "doesnt exist" << endl;
}
即使输入的字符存在于name 字符串数组中,if 语句似乎总是为真并运行代码。
【问题讨论】:
-
看看
std::string::find()返回什么。不是字符而是位置,如果找不到字符,则返回std::string::npos。