特定の状況では、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 を使用する方がエレガントですが、パフォーマンス上の理由から、文字を直接比較する方が速いでしょうか?