gpt4 book ai didi

字符串匹配alg的c++实现

转载 作者:行者123 更新时间:2023-11-28 07:28:20 32 4
gpt4 key购买 nike

我正在为用户名数据库实现字符串匹配算法。我的方法采用现有的用户名数据库和用户想要的新用户名,然后检查用户名是否已被占用。如果采用该方法,则该方法应该返回带有数据库中未采用的数字的用户名。

例子:

“贾斯汀”,“贾斯汀1”,“贾斯汀2”,“贾斯汀3”

输入“贾斯汀”

返回:“Justin4”,因为 Justin 和编号为 1 到 3 的 Justin 已经被占用。

我已经用Java写过这段代码,现在我正在用C++写它来练习。我有一些问题:

  1. 如何比较两个字符串?我已经尝试过 strcmp 和其他几个,但我总是收到错误消息:无法将参数 2 的 std::string 转换为 const char*。

  2. 如何连接一个整数和一个字符串?在 Java 中,它就像使用 + 运算符一样简单。

  3. 在我的主函数中,它表示没有匹配的函数调用 Username::NewMember(std::string, std::string)。为什么它不能识别 main 中的 newMember?

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

    class Username {
    public:



    string newMember(string existingNames, string newName){

    bool found = false;
    bool match = false;
    string otherName = NULL;

    for(int i = 0; i < sizeof(existingNames);i++){
    if(strcmp(existingNames[i], newName) == 0){
    found = true;
    break;
    }

    }
    if(found){
    for(int x = 1; ; x++){
    match = false;
    for(int i = 0; i < sizeof(existingNames);i++){
    if(strcmp(existingNames[i],(newName + x)) == 0){
    match = true;
    break;
    }

    }
    if(!match){
    otherName = newName + x;
    break;
    }

    }

    return otherName;

    }





    else return newName;




    }

    int main(){


    string *userNames = new string[4];
    userNames[0] = "Justin";
    userNames[1] = "Justin1";
    userNames[2] = "Justin2";
    userNames[3] = "Justin3";

    cout << newMember(userNames, "Justin") << endl;

    delete[] userNames;

    return 0;


    }
    }

最佳答案

好的,您的代码中有一些错误:

  • 如果你想比较两个string s,只需使用 operator== : string == string2

  • 如果您想在 C++ 中将 int 附加到 string,您可以使用 streams :

    #include <sstream>

    std::ostringstream oss;
    oss << "Justin" << 4;
    std::cout << oss.str();
  • 您正在将 string* 传递给函数 newMember 但您的原型(prototype)与它不匹配:

     string *userNames = new string[4];
    newMember(userNames, "Justin"); // Call

    string newMember(string existingNames, string newName); // Protype

    我认为应该是:string newMember(string* existingNames, string newName); 否?

  • 在示例中,您的main 函数在您的类Username 中。它在 C/C++ 中是不正确的。与 Java 不同,main 函数处于全局范围内。

  • 最后你应该使用 const-reference parameter因为你不需要修改它们的内容,你也需要复制它们:

    string newMember(string* existingNames, const string& newName);
    // ^^^^^ ^

你确定你需要在主函数中动态分配一些东西吗?

关于字符串匹配alg的c++实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18297024/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com