编写一个函数利用指针在字符串s中的指定位置pos处这里插入的位置是从1开始不是下标插入字符串。插入的位置和内容是从键盘输入要求:子函数 char InsertStrchar sint poschar t
#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;
}
``
原文地址: https://www.cveoy.top/t/topic/fbm2 著作权归作者所有。请勿转载和采集!