繁体   English   中英

如何检查一个字符串的字母是否在另一个字符串中以给定顺序存在?

[英]How to check whether the letters of a string exist in the given order within another string?

我正在尝试"nadia"一个程序来检查单词"nadia"是否存在于字符串中。 如果您可以删除零个或多个字符来获取此单词,则应打印"YES"否则应打印"NO" 谁能帮助我找到我缺少的测试用例? 当我尝试提交它时,它说输出错误。

这是我的代码:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;

bool nadiaFound(string s){
    int counter = 0;
    char key[5] = { 'n', 'a', 'd', 'i', 'a' };
    for (int i = 0; i < s.size(); i++){
        if (s[i] == key[counter]){
            counter++;
        }
    }
    if (counter == 5){
        return true;
    }
    else { return false; }
}
int main(){
    int T;
    cin >> T;
    string *names = new string[T];

    for (int i = 0; i < T; i++){
        cin >> names[i];
    }
    bool *barr = new bool[T];

    for (int i = 0; i < T; i++){
        barr[i] = false;
    }

    for (int i = 0; i < T; i++){
        if (nadiaFound(names[i])){
            barr[i] = true;
        }
        else{
            barr[i] = false;
        }
    }
    for (int i = 0; i < T; i++){
        if (barr[i]){
            cout << "YES" << endl;
        }
        else {
            cout << "NO" << endl;
        }
    }
    return 0;
}

您可能在访问key[counter]导致未定义行为时访问绑定内存不足。 一种可能的解决方法是:

for (int i = 0; i < s.size(); i++){
    if (s[i] == key[counter]){
        if(++counter == 5) break;
        // ^^        ^^^^  ^^^^^
    }
}

for原样重写for (int i = 0; i < s.size() && counter < 5; i++)

这也可以工作:

#include <iostream>
#include <string>
using namespace std;

int main(){
    string names; 
    getline(cin,names); 
    cout << names << endl;
    if (names.find("a", names.find("i", names.find("d", names.find("a", names.find("n", 0))))) != string::npos)
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
    return 0;
}

函数查找的结果返回指向字符串中搜索字符串开始的第一个位置或搜索到的char所在的位置(取决于变体)。

如果搜索失败,则两个函数都将返回一个特殊值,表示为string::npos (此值在字符串成员函数中用作len(或sublen)参数的值时,表示“直到字符串结尾”。) 。 您可以使用它来检查您的干草堆中是否包含所需的发现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM