C言語:strcmp関数をシミュレートします



C Language Simulate Strcmp Function



まず、strcmp関数の関数と使用法を見てみましょう。2つの文字列を比較します。これらの2つの文字列をstr1、str2とします。str1がstr2と等しい場合、str1がstr2より小さい場合はゼロを返し、str1がtr2より大きい場合は負の数を返し、正の数を返します。

次に、このstrcmp関数を実装する方法を見てみましょう。
基本的な考え方は、最初にこれら2つの文字列を指す2つのポインタを定義し、次に両方の文字列が「 0」でなく、ポインタが指す位置の文字が等しい場合、2つのポインタ変数は後方に移動します。 、次の文字が比較され、ループが順番に実行されます。最終結果は、最初の文字列の現在の位置の値から2番目の文字列の現在の位置の値を引いた値を返します。ループが終了し、2つの文字列が完全に等しい場合、0が返されます。真ん中の文字に移動し、2つの文字列が等しくない場合、この位置にある2つの文字列の差が返されます。



具体的な実装コードは次のとおりです。

#include #include #include int my_strcmp(const char* str1, const char* str2) { assert(str1 != NULL) assert(str2 != NULL) /*If the strings are all equal, then both strings reach'' at the end of the loop, and the subtraction is 0. If the characters at a certain position are found to be different in the middle of the loop, Then subtract the ASCII values ​​of the two characters at that position */ while ( (*str1 == *str2) && (*str1 != '')) { str1++ str2++ } return *str1 - *str2 } int main() { char* str1 = 'ef' char* str2 = 'efa' int ret = 0 ret = my_strcmp(str1, str2) printf('%d ', ret) system('pause') return 0 }

結果は次のとおりです。
画像