我有一些代码在一个函数中大量使用 strcasecmp
(参见版本 1)。所以我想知道我是否应该将它更改为大写或小写和 strcmp
(如版本 2)以兼容 c 并具有更好的性能,因为我只需要将其转换为大写- 或者小写一次。
char pname[5]="TEST";
//version 1
if(strcasecmp(pname,"TEST")==0)
{
printf("%s\n", pname);
}
//version 2
for(int i=0;i<5;++i)
{
pname[i]=toupper(pname[i]);
}
if(strcmp(pname,"TEST")==0)
{
printf("%s\n", pname);
}
最佳答案
我假设更好,你的意思是,更好的性能,即更少的操作。
假设:
x = time of tolower()/toupper()
n = time of string[n] operation
还有
best case (quickest time to complete) = no match
worst case (longest time to complete) = string match
这些计算假设我们只需要降低/提升一个字符串,如您的代码所示
版本 1:(strcasecmp)
best case = 1 + x [i.e. one operation on to lower/upper on first character - no match]
worst case = n + (x * n) [i.e. n operations of to lower/upper - string match]
-- average = (n*(x+1) + x + 1)/2
版本 2(tolower/upper + strcmp)
best case = 1 + (x * n) [i.e. n operations of to lower/upper on all character - no match]
worst case = n [i.e. n operations on all characters]
-- average = (1 + n*(x+1)) / 2
结论
所以与版本 2 的不同之处在于,它改进了最坏的情况,但这样做却使最好的情况变得更糟。然而,在一般情况下,版本 2 更快。
即如果您像之前的版本 2 一样将整个字符串更改为大写或小写,那么您必须已经遍历字符串中的每个字符,这可能不需要,因为字符串可能根本不匹配,添加额外的操作不需要。
此外,根据您使用的编译器,使用索引的 for 循环不是特别快,您可以更快:
while (*chptr)
{
// do stuff with *chptr
chptr++;
}
对于字符串。
关于c - strcasecmp 或 tolower/toupper + strcmp 哪个更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51418990/