我想知道是否在某些情况下,通过直接比较字符来比较字符串会更少处理器密集型,而不是使用strcmp。使用strcmp比较字符串与直接比较字符
对于一些背景信息,我在C编码嵌入式系统中没有太多的处理能力。它必须读取传入的字符串并根据传入的字符串执行某些任务。
说输入的字符串是"BANANASingorethispartAPPLESignorethisalsoORANGES"
。我想验证BANANAS
,APPLES
和ORANGES
是否存在于其确切位置。我的代码这样做:
input = "BANANASingorethispartAPPLESignorethisalsoORANGES";
char compare[100]; //array to hold input to be compared
strncopy(compare,input,7); //copy "BANANAS" to compare
compare[7] = "\0"; //terminate "BANANAS"
if (strcmp(compare, "BANANAS") == 0){
strncopy(compare,input[21],6); //copy "APPLES" to compare
compare[6] = "\0"; //terminate "APPLES"
if(strcmp(compare,"APPLES")==0){
//repeat for "ORANGES"
}
}
或者,我可以直接比较的字符:
input = "BANANASingorethispartAPPLESignorethisalsoORANGES";
if(input[0]=='B' && input[1]=='A' && input[2]=='N' && input[3]=='A' && input[4]=='N' && input[5]=='A' && input[6]=='S'){
if(input[21]=='A' && input[22]=="P" <snipped>){
if(input[30]=='O' <snipped>){
//input string matches my condition!
}
}
}
使用strncopy + STRCMP更优雅,但对于性能方面的原因,只是直接比较的字符会是更快?
我相信'strcmp()'为'strlen()'等优化你不用担心这一点。 –
如果标准库为您提供诸如字符串比较之类的功能,则应始终偏好这些。 –
我相信你花时间写这个问题的时间要比采用这两个选项中最好的选项所获得的性能增益重要得多。 –