#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <stdlib.h> #include <string.h> void insert_string(char* dest, const char* src, int pos);//在dest字符串中pos位置插入字符串src int main() { char original[100]; char toInsert[10]; int position = 7; gets(original); scanf("%d\n", &position); gets(toInsert); insert_string(original, toInsert, position); printf("%s\n", original); return 0; } void insert_string(char* dest, const char* src, int pos) { }
只要求写入局部的insert函数,重写的代码如下:
int len = strlen(dest); int le = strlen(src); //每个字符要移动的方块数应该是strlen(src),而不是pos for (int i = len - 1; i >= pos; i--) { dest[i + le] = dest[i]; } dest[len - 1 + le+1] = 0; int t = 0; //开始插入 for (int i = pos; i <= pos + le- 1; i++) { dest[i] = src[t]; t++; }
要移动的第一个字符就是你要在原字符里插入新字符串的首个位置
字符串问题,最先检查的是“删除最后多余的\n”
//gets
函数不会将换行符存储在数组中。换句话说,gets
会将换行符替换为字符串的结束符(\0
),原来gets还有比fgets更好的地方!
最后检查的是“字符串末尾是否有\0”
//puts在输出字符串后,puts
会自动添加一个换行符(\n
),这意味着他能自动换行!
注:都只能用于字符串
“在 C 语言中,puts
函数专门用于输出以 null 字符(\0
)结尾的字符串,而不是单个字符”
Comments NOTHING