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

本文将介绍如何在C语言中实现一个字符串插入函数,该函数可以将指定字符插入到字符串的指定位置。

函数定义:

void insertc(char *str, char c, int n) {
    int len = strlen(str);
    if (n < 0 || n > len) {
        return; // 插入位置非法
    }
    // 计算插入后字符串的长度
    int new_len = len + 1;
    // 如果新长度超过原字符串长度,则重新分配内存
    char *new_str = (char *)realloc(str, new_len);
    if (new_str == NULL) {
        return; // 内存分配失败
    }
    // 将插入位置之后的字符往后移动一个位置
    for (int i = len; i >= n; i--) {
        new_str[i + 1] = new_str[i];
    }
    // 在插入位置处插入指定字符
    new_str[n] = c;
    // 在字符串末尾添加一个空字符
    new_str[new_len] = '\0';
    // 将指针指向新分配的内存
    str = new_str;
}

函数说明:

  1. 函数参数:

    • str: 指向要插入的字符串的指针。
    • c: 要插入的字符。
    • n: 插入位置,从0开始计数。
  2. 函数功能:

    • 检查插入位置是否合法,如果非法则返回。
    • 计算插入后字符串的长度。
    • 重新分配内存空间,如果失败则返回。
    • 将插入位置之后的字符往后移动一个位置。
    • 在插入位置处插入指定字符。
    • 在字符串末尾添加一个空字符。

主函数演示:

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

void insertc(char *str, char c, int n) {
    // ... (函数代码同上)
}

int main() {
    char str[] = 'hello';
    char c = 'C';
    int n = 6;
    printf('原始字符串: %s\n', str);
    insertc(str, c, n);
    printf('插入后的字符串: %s\n', str);
    return 0;
}

样例输入:

hello
C
6

样例输出:

原始字符串: hello
插入后的字符串: helloC

总结:

本文通过编写一个简单的字符串插入函数,演示了如何在C语言中实现字符串的插入功能。在实际应用中,我们可以根据具体的需求对函数进行修改和扩展。

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

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

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