题解 | #表示数字#
表示数字
https://www.nowcoder.com/practice/637062df51674de8ba464e792d1a0ac6
#include <stdio.h> #include <string.h> #include <ctype.h> void InsertCharIntoStr(char *str, int len, int idx, char ch); void AddPreAndPostStar(char *str); int main() { char str[300] = ""; fgets(str, 300, stdin); AddPreAndPostStar(str); puts(str); return 0; } //说明:预先保证有足够的空间 //str最后一个元素的idx = strlen(str)-1 //函数功能:向指定位置 idx 之前,插入一个字符 ch. void InsertCharIntoStr(char *str, int len, int idx, char ch) { if(str==NULL) return; if(len <= 0 || idx < 0 || idx > len) return; //idx 的可行范围[0, len] //向索引 idx 插入ch, 那么str[idx] = ch。 后面的字符全部向后移动1格。 for(int j=len; j>idx; j--) { str[j] = str[j-1]; } str[idx] = ch; } void AddPreAndPostStar(char *str) { if(str == NULL) return; int isNumHead = 0; // int len = strlen(str); for(int i=0; str[i]!='\0'; i++) { if((isNumHead== 0) && isdigit(str[i])) { //这道题有二义性:当数字前、后已经有星号,是否需要加星号。 //从给出的结果来看,数字前后已经有星号,也要加星号。因此这句话注释了 //if((i>0 && isdigit(str[i-1])!= '*')||i=0) { isNumHead = 1; InsertCharIntoStr(str, strlen(str), i, '*'); i++; } } #endif #if 1 //这道题有二义性:当数字前、后已经有星号,是否需要加星号。 //从给出的结果来看,数字前后已经有星号,也要加星号。因此这句话注释了 //if(isdigit(str[i]) && (!isdigit(str[i+1])) &&(str[i+1]!='*')) if(isdigit(str[i]) && (!isdigit(str[i+1]))) { isNumHead = 0; InsertCharIntoStr(str, strlen(str), i+1, '*'); i += 2; } #endif } }