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

本文将介绍如何编写一个C语言函数 void insertc(char *str, char c, int n),该函数可以将字符 c 插入在 str 所指字符串的第 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("源字符串:");
    scanf("%s", str);
    printf("单字符:");
    scanf(" %c", &c);
    printf("插入位置n:");
    scanf("%d", &n);
    insertc(str, c, n);
    printf("插入结果:%s\n", str);
    return 0;
}

输入输出格式

输入形式:

源字符串

单字符

插入位置n

输出形式:

插入结果

样例输入

hello C 6

样例输出

helloC

总结

本文详细介绍了编写C语言字符串插入函数 void insertc(char *str, char c, int n) 的方法,并提供了完整的代码示例和输入输出格式,希望能帮助读者更好地理解和使用该函数。

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

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

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