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

本文介绍了使用C语言编写一个函数,利用指针在字符串中指定位置插入另一个字符串。函数通过键盘输入插入的位置和内容,并返回插入后的新字符串。

代码实现

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

char *InsertStr(char *s, int pos, char *t) {
    int len1 = strlen(s);
    int len2 = strlen(t);
    if (pos < 1 || pos > len1 + 1) {
        printf('Invalid position!\n');
        return s;
    }
    char *new_s = (char *)malloc(sizeof(char) * (len1 + len2 + 1));
    strncpy(new_s, s, pos - 1);
    strncpy(new_s + pos - 1, t, len2);
    strncpy(new_s + pos - 1 + len2, s + pos - 1, len1 - pos + 1);
    new_s[len1 + len2] = '\0';
    return new_s;
}

int main() {
    char s[100], t[100];
    int pos;
    printf('Enter the original string: ');
    scanf('%s', s);
    printf('Enter the position to insert (starting from 1): ');
    scanf('%d', &pos);
    printf('Enter the string to insert: ');
    scanf('%s', t);
    char *new_s = InsertStr(s, pos, t);
    printf('The new string is: %s\n', new_s);
    free(new_s);
    return 0;
}

代码说明

  • 函数 InsertStr 接受三个参数:
    • s: 原字符串
    • pos: 插入位置(从1开始)
    • t: 要插入的字符串
  • 函数首先检查插入位置是否有效。
  • 如果位置有效,函数会分配一个新的字符串,并使用 strncpy 函数将原字符串、插入字符串和剩余部分分别复制到新字符串中。
  • 最后,函数返回新的字符串。

代码示例

Enter the original string: hello
Enter the position to insert (starting from 1): 3
Enter the string to insert: world
The new string is: helloworld

总结

本函数利用指针和 strncpy 函数实现了在字符串指定位置插入另一个字符串的功能。该函数可以用于各种字符串操作场景。

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

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

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