从键盘录入一个字符串,在其中的每一个数字字符之后添加一个字符@
3条回答 默认 最新
- Cat_贰龄依旧 2021-12-07 11:46关注
如果要生成新的字符串, 就应该用 calloc 得到一个新的内存空间,
新字符串的长度 = 原字符串长度 + 数字个数;
然后将原来的字符串复制过来, 复制过程中, 遇到数字就在后面增加一个 '@';#include <stdio.h> #include <stdlib.h> char* InsertAfterNum(char* str, char ch) { if (nullptr == str || '\0' == ch) { return str; } char now = 0; int i = 0; int j = 0; for (; '\0' != (now = str[i]); ++i) { if ('0' <= now && '9' >= now) { ++j; } } char* res = (char*) calloc(i + j, sizeof(char)); j = 0; for (i = 0; '\0' != (now = str[i]); ++i, ++j) { res[j] = now; if ('0' <= now && '9' >= now) { res[++j] = ch; } } return res; } int main(int argc, char** argv) { char str[32] = ""; scanf("%s", str); char* ans = InsertAfterNum(str, '@'); printf("%s\n", ans); free(ans); return scanf("%*s"); }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录