C语言字符串插入函数:在指定位置插入字符

功能描述:

编写函数 void insertc(char *str, char c, int n),将字符 c 插入在 str 所指字符串的第 n 个位置。

要求:

在主函数中输入字符串、字符及插入位置,调用函数后输出插入结果。例如:在 'abcdedg' 的第 5 个位置插入 'm',插入结果 'abcdmedg' 。

代码实现:

#include <stdio.h>
#include <string.h>

void insertc(char *str, char c, int n) {
    int len = strlen(str);
    if (n < 1 || n > len + 1) {
        printf("插入位置非法!\n");
        return;
    }
    for (int i = len; i >= n; i--) {
        str[i + 1] = str[i];
    }
    str[n] = c;
}

int main() {
    char str[100];
    char c;
    int n;
    printf("源字符串:\n");
    scanf("%s", str);
    printf("单字符:\n");
    scanf(" %c", &c);
    printf("插入位置n:\n");
    scanf("%d", &n);
    insertc(str, c, n);
    printf("插入结果:\n%s\n", str);
    return 0;
}

输入格式:

源字符串

单字符

插入位置 n

输出格式:

插入结果

样例输入:

hello
C
6

样例输出:

helloC
C语言字符串插入函数:在指定位置插入字符

原文地址: https://www.cveoy.top/t/topic/odAt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录