c言語| | atoi関数を自分で実装する



C Language Implement Atoi Function Yourself



まず、atoi関数を紹介します。atoi関数は、文字列を数値に変換する関数です。

例:「hjads7809809」は「7809809」になります



my_atoi関数を見てみましょう。

コードは次のように表示されます。



#include #include #include #include #include enum State // State { VALID, // legal, the string is all numeric characters is legal INVALID // Illegal, not all character strings are numeric characters } // Set the starting state to be illegal enum State state = INVALID int my_atoi(const char* str) { int flag = 1 long long ret = 0 // Null pointer assert(str != NULL) // Empty string if (*str == '') { return 0 } // Skip whitespace characters while (isspace(*str)) { str++ } // Positive and negative if (*str == '+') { str++ } if (*str == '-') { flag = -1 str++ } while (*str) { if (isdigit(*str)) { ret = ret * 10 + flag * (*str - '0') if (ret INT_MAX) { return 0 } } else { return 0 } str++ } state = VALID return (int)ret } int main() { char str[] = ' -1781hjk' int ret = my_atoi(str) if (state == VALID) { // The output is legal printf('%d ', ret) } return 0 }

実装時に状態変数を追加しました。文字列が有効な場合は状態が出力され、そうでない場合は出力されません。

法的な例: '-3712987'

文字列に正と負の記号と数字のみが含まれている場合、文字列は有効です。それ以外の場合は無効です。