不多赘述,可以看书本。
最重要的是可以通过比较两个指针的值(即他们的地址),判断其中一个指针有没有向前移动。
1 /******************************************************************* 2 Copyright(c) 2016, Harry He 3 All rights reserved. 4 5 Distributed under the BSD license. 6 (See accompanying file LICENSE.txt at 7 https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt) 8 *******************************************************************/ 9 10 //================================================================== 11 // 《剑指Offer——名企面试官精讲典型编程题》代码 12 // 作者:何海涛 13 //================================================================== 14 15 // 面试题20:表示数值的字符串 16 // 题目:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如, 17 // 字符串“+100”、“5e2”、“-123”、“3.1416”及“-1E-16”都表示数值,但“12e”、 18 // “1a3.14”、“1.2.3”、“+-5”及“12e+5.4”都不是 19 20 #include <stdio.h> 21 22 bool scanUnsignedInteger(const char **str); 23 bool scanInteger(const char **str); 24 25 // 数字的格式可以用A[.[B]][e|EC]或者.B[e|EC]表示,其中A和C都是 26 // 整数(可以有正负号,也可以没有),而B是一个无符号整数 27 bool isNumeric(const char *str) 28 { 29 if (str == nullptr) 30 return false; 31 32 bool numeric = scanInteger(&str); 33 34 // 如果出现'.',接下来是数字的小数部分 35 if (*str == '.') 36 { 37 ++str; 38 39 // 下面一行代码用||的原因: 40 // 1. 小数可以没有整数部分,例如.123等于0.123; 41 // 2. 小数点后面可以没有数字,例如233.等于233.0; 42 // 3. 当然小数点前面和后面可以有数字,例如233.666 43 numeric = scanUnsignedInteger(&str) || numeric; 44 } 45 46 // 如果出现'e'或者'E',接下来跟着的是数字的指数部分 47 if (*str == 'e' || *str == 'E') 48 { 49 ++str; 50 51 // 下面一行代码用&&的原因: 52 // 1. 当e或E前面没有数字时,整个字符串不能表示数字,例如.e1、e1; 53 // 2. 当e或E后面没有整数时,整个字符串不能表示数字,例如12e、12e+5.4 54 numeric = numeric && scanInteger(&str); 55 } 56 57 return numeric && *str == '