C ++字符串比较算法 [英] c++ string compare algorithm
问题描述
什么是您最好的字符串比较算法?
what is your best string comparison algorithm?
我觉得为O(n)
#include <string>
bool str_cpmr(char* str1, char* str2)
{
int l1 = strlen(str1), l2 = strlen(str2) ;
if(l1 != l2)
return false;
for(int i = 0 ; i < l1 ; i++)
if(str1[i] != str2[i])
return false ;
return true ;
}
和我不知道是否有其他/更好的解决方案。
and i wonder if there is any other / better solution.
另外,如何测试准确?
我建议比较
- 在100场比赛
- 100串个字符交换不同
有更多的测试字符串比较?
is there more to test string compare ?
它是如何在STL C ++(SLT字符串::比较)?
how is it in stl c++ (slt string::compare) ?
谢谢!!!!!
推荐答案
您的功能是为O(n),但仍需要大约一倍所需的时间 - 的strlen
散步通过串找到的长度,然后(假设它们是相同的长度),则通过字符串走路了比较字符。
You function is O(n), but still takes roughly double the time necessary -- strlen
walks through the string to find the length, then (assuming they're the same length) you walk through the strings again comparing the characters.
相反的是,我宁愿穿越琴弦,直到你到达一个不匹配或两个字符串的结束。如果你达到不匹配,则返回false。你返回true,当且仅当您没有任何的不匹配首先到达两个字符串(同时)结束。
Instead of that, I'd walk through the strings until you reach a mismatch or the end of both strings. If you reach a mismatch, you return false. You return true if and only if you reach the end of both strings (simultaneously) without any mismatches first.
这篇关于C ++字符串比较算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!