1. 程式人生 > 實用技巧 >面試題20:表示數值的字串

面試題20:表示數值的字串

考察字串匹配:這個題目的指標運用特別有意思。注意第30行程式碼,傳遞的是陣列的地址,那麼在函式中就有可能改變當前指標的地址,後面再使用*str就可能不會再指向陣列首位了。

C++版

#include <iostream>
#include <algorithm>
using namespace std;

bool scanUnsignedInteger(char** str)
{
    char* before = *str;
    while(**str != '\0' && **str >= '0' && **str <= '9')
        ++(*str);

    // 當str中存在若干0-9的數字時,地址肯定增加了,大於原來的before地址,返回true
    return *str > before;
}

// 整數的格式可以用[+|-]B表示, 其中B為無符號整數
bool scanInteger(char** str)
{
    if(**str == '+' || **str == '-')
        ++(*str);
    return scanUnsignedInteger(str);
}

// 數字的格式可以用A[.[B]][e|EC]或者.B[e|EC]表示,其中A和C都是
// 整數(可以有正負號,也可以沒有),而B是一個無符號整數
bool isNumeric(char* str)
{
    if(str == nullptr)
        return false;

    bool numeric = scanInteger(&str);

    // 如果出現'.',接下來是數字的小數部分
    if(*str == '.')
    {
        ++str;

        // 下面一行程式碼用||的原因:
        // 1. 小數可以沒有整數部分,例如.123等於0.123;
        // 2. 小數點後面可以沒有數字,例如233.等於233.0;
        // 3. 當然小數點前面和後面可以有數字,例如233.666
        numeric = scanUnsignedInteger(&str) || numeric;
    }

    // 如果出現'e'或者'E',接下來跟著的是數字的指數部分
    if(*str == 'e' || *str == 'E')
    {
        ++str;

        // 下面一行程式碼用&&的原因:
        // 1. 當e或E前面沒有數字時,整個字串不能表示數字,例如.e1、e1;
        // 2. 當e或E後面沒有整數時,整個字串不能表示數字,例如12e、12e+5.4
        numeric = numeric && scanInteger(&str);
    }

    return numeric && *str == '\0';
}


int main()
{

    return 0;
}