【问题标题】:Checking if a string contains a substring C++检查字符串是否包含子字符串 C++
【发布时间】:2021-12-20 09:05:01
【问题描述】:

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

这是我的代码:

#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;
}

这是我遇到的问题:

有什么想法吗?

【问题讨论】:

  • char 数据类型没有查找功能
  • 您不使用std::string 有什么原因吗?那个确实有find 方法。如果出于某种原因你坚持要处理 C 风格的字符串,你正在寻找 strstr 函数。
  • 既然您想用 c++ 编写,这可能会回答您的问题。 stackoverflow.com/questions/2340281/…
  • @IgorTandetnik 这是我第一次用 c++ 编写代码:P 所以我真的不知道我在做什么
  • @AngelosFr 是的,这就是我试图关注的帖子,但我无法让它工作,我不知道为什么:(

标签: c++ string substring


【解决方案1】:

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 这样做是合法的。

【讨论】:

  • 是的,工作,谢谢!我不知道您可以使用std::string 代替char。第一次使用 C++,我已经习惯了 C 中的 char
猜你喜欢
  • 2011-11-09
  • 2013-05-18
  • 2014-11-22
  • 2013-02-05
  • 1970-01-01
  • 2021-12-14
  • 2011-01-21
  • 1970-01-01
  • 2013-03-04
相关资源
最近更新 更多