我想知道在某些情况下,通过直接比较字符来比较字符串会减少处理器密集度,而不是使用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更优雅,但出于性能原因,直接比较字符会更快吗?
答案 0 :(得分:2)
直接比较字符是相当卑鄙和脆弱的代码。根据编译器和体系结构的不同,优化也可能更难。
另一方面,你的副本是浪费 - 它没有任何用处。
只需检查字符串至少足够长(或完全正确的长度,但不能太短)并strncmp
(或memcmp
)就位
#define COMPARE(IN, OFF, SUB) memcmp(IN+OFF, SUB, sizeof(SUB)-1)
input = "BANANASingorethispartAPPLESignorethisalsoORANGES";
if (COMPARE(input, 0, "BANANAS") == 0 &&
COMPARE(input, 21, "APPLES" ) == 0 &&
COMPARE(input, 40, "ORANGES") == 0) )
{
答案 1 :(得分:2)
在您的情况下,您最好使用memcmp()
来避免复制数据:
input = "BANANASingorethispartAPPLESignorethisalsoORANGES";
if (memcmp(input, "BANANAS", 7) == 0 &&
memcmp(input+21, "APPLES", 6 ) == 0 &&
memcmp(input+40, "ORANGES", 8 ) == 0 )
{
// everything matches ...
}
至少一些memcmp()
的实现甚至比通过char比较char更快。