检查字符串是否包含子字符串 C++

问题描述 投票:0回答:1

我正在尝试编写一个程序来检查一个字符串是否包含另一个字符串的子字符串,但它不起作用。

这是我的代码:

#include <iostream>
#include <algorithm>

using namespace std;

//Struct to store information
struct strings {
    char string1[20], string2[20];
} strings;

//Function to check if the strings are equal
void equalCheck(){
    int check = 0, i = 0;
    while (strings.string1[i] != '\0' || strings.string2[i] != '\0'){
        if (strings.string1[i] != strings.string2[i]){
            check = 1;
            break;
        }
        i++;
    }
    if (check == 0){
        cout << "The strings are equal" << endl;
    }
    else
        cout << "The strings are not equal" << endl;

}

//Function to check for a substring
void substringCheck(){
    if (strings.string1.find(strings.string2) != string::npos) {
        cout << "found!" << '\n';
    }

}

int main() {


    //Ask the user for two strings
    cout << "Please type the first string: ";
    cin >> strings.string1;
    cout << "Please type the second string: ";
    cin >> strings.string2;

    //Prints out the two strings
    //cout << "The two strings are " << strings.string1 << " and " << strings.string2;

    equalCheck();
    substringCheck();

    return 0;
}

这是我遇到的问题:

有什么想法吗?

c++ string substring
1个回答
2
投票

strings
有两个
std::string
而不是两个
char[20]
不是更容易吗?

那么你就可以毫无问题地说出这句话了:

if (strings.string1.find(strings.string2) != std::string::npos) {
    std::cout << "found!\n";
}

char
不是像
std::string
那样的类,它没有任何成员函数。这意味着
char[20].find
不存在。然而,
std::string
是一个类。它确实有一个名为
std::string::find()
的成员函数,因此对
std::string
执行此操作是合法的。

© www.soinside.com 2019 - 2024. All rights reserved.