0

我想知道在某些情况下,与使用 strcmp 相比,通过直接比较字符来比较字符串是否会减少处理器密集型。

对于一些背景信息,我在一个处理能力不强的嵌入式系统中使用 C 进行编码。它必须读取传入的字符串并根据传入的字符串执行某些任务。

假设传入的字符串是"BANANASingorethispartAPPLESignorethisalsoORANGES". 我想验证BANANASAPPLESORANGES是否存在于它们的确切位置。我的代码会这样做:

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 更优雅,但是出于性能原因,直接比较字符会更快吗?

4

2 回答 2

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) )
{
于 2013-06-26T14:22:07.250 回答
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()甚至会比逐个字符比较更快。

于 2013-06-26T14:24:47.050 回答