字符串匹配算法的c++实现

c++ implementation of string matching alg

本文关键字:实现 c++ 匹配算法 字符串      更新时间:2023-10-16

我正在为用户名数据库实现字符串匹配算法。我的方法使用现有的用户名数据库和用户想要的新用户名,并检查用户名是否被使用。如果采用了该方法,则该方法应该返回一个没有在数据库中采用的数字的用户名。

示例:

"Justin"、"Justin1"、"贾斯汀2"、"贾斯汀3"

输入"Justin"

return:"Justin4",因为Justin和数字为1到3的Justin已经被拿走了。

我已经用Java编写了这段代码,现在我正在用C++进行练习。不过我有一些问题:

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

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

  3. 在我的主函数中,它表示Username::NewMember(std::string,std::字符串)没有匹配的函数调用。为什么它主要不承认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,只需使用operator==:string == string2

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

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

     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参数,因为您不需要修改它们的内容,也需要复制它们:

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

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