字符串匹配算法的c++实现
c++ implementation of string matching alg
我正在为用户名数据库实现字符串匹配算法。我的方法使用现有的用户名数据库和用户想要的新用户名,并检查用户名是否被使用。如果采用了该方法,则该方法应该返回一个没有在数据库中采用的数字的用户名。
示例:
"Justin"、"Justin1"、"贾斯汀2"、"贾斯汀3"
输入"Justin"
return:"Justin4",因为Justin和数字为1到3的Justin已经被拿走了。
我已经用Java编写了这段代码,现在我正在用C++进行练习。不过我有一些问题:
-
你如何比较两个字符串?我尝试过strcmp和其他一些方法,但总是收到错误消息:无法将参数2的std::string转换为const char*。
-
如何连接int和字符串?在java中,它就像使用+运算符一样简单。
-
在我的主函数中,它表示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); // ^^^^^ ^
你确定你需要在主函数中动态分配一些东西吗?
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的