【问题标题】:How to check if char doesnt exist in a string如何检查字符串中是否不存在char
【发布时间】: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

标签: c++ arrays string char


【解决方案1】:

我的方法的问题在于,我在 if 条件下检查了一个 's' 字符与数组的索引位置。

相反,做:

    if (name.find(characterToFind) == std::string::npos) {
       cout << "doesnt exist" << endl;
    }

这是检查字符输入是否等于不存在的位置!这是真的,所以它告诉用户输入的字符不存在。

【讨论】:

    猜你喜欢
    • 2016-08-03
    • 2020-11-29
    • 2011-07-30
    • 2016-12-11
    • 2021-08-25
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多