插入子串* 分数 10 作者 李祥 单位 湖北经济学院 请编写函数,在目的串中插入源串。 函数原型 char* StrInsert(char *dst, int idx, const char *src); 说明:dst 为指示目的串起始地址的指针,idx 为插入位置(下标),src 为指示源串起始地址的指针。函数在目的串 dst 下标 idx 处插入源串 src,函数值为 dst。若 idx 不正确,则不插入子串。 要求:直接在原数组上完成操作,不要借助其它数组。 裁判程序 #include <stdio.h> char* StrInsert(char *dst, int idx, const char *src); int main() { char a[1024], b[1024]; int i; gets(a); scanf("%d%*c", &i); gets(b); StrInsert(a, i, b); puts(a); return 0; } /* 你提交的代码将被嵌在这里 */
时间: 2024-03-13 09:48:03 浏览: 20
```
#include <stdio.h>
#include <string.h>
char* StrInsert(char *dst, int idx, const char *src) {
int dst_len = strlen(dst);
int src_len = strlen(src);
int i;
if (idx < 0 || idx > dst_len) {
return dst;
}
for (i = dst_len; i >= idx; i--) {
*(dst + i + src_len) = *(dst + i);
}
for (i = 0; i < src_len; i++) {
*(dst + i + idx) = *(src + i);
}
return dst;
}
int main() {
char a[1024], b[1024];
int i;
gets(a);
scanf("%d%*c", &i);
gets(b);
StrInsert(a, i, b);
puts(a);
return 0;
}
```
相关问题
用C语言编写函数 统计子串sub在母串中的出现次数
以下是用C语言编写函数统计子串在母串中出现次数的示例代码:
```c
#include <stdio.h>
#include <string.h>
int countSubstring(char *str, char *sub) {
int count = 0;
int len1 = strlen(str);
int len2 = strlen(sub);
for (int i = 0; i <= len1 - len2; i++) {
int j;
for (j = 0; j < len2; j++) {
if (str[i + j] != sub[j]) {
break;
}
}
if (j == len2) {
count++;
}
}
return count;
}
int main() {
char str[] = "hello world, world is beautiful";
char sub[] = "world";
int count = countSubstring(str, sub);
printf("'%s' appears %d times in '%s'\n", sub, count, str);
return 0;
}
```
输出结果为:
```
'world' appears 2 times in 'hello world, world is beautiful'
```
2.设计函数char *insert(s1,s2,n),用指针实现在字符串S1中指定的位置N处插入字符串S2。
以下是实现该函数的代码:
```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *insert(char *s1, char *s2, int n) {
int len1 = strlen(s1);
int len2 = strlen(s2);
if (n > len1 || n < 0) {
printf("Error: Invalid position!\n");
return s1;
}
char *new_s = (char *)malloc(sizeof(char) * (len1 + len2 + 1));
strncpy(new_s, s1, n);
strncpy(new_s + n, s2, len2);
strncpy(new_s + n + len2, s1 + n, len1 - n);
new_s[len1 + len2] = '\0';
free(s1);
return new_s;
}
int main() {
char s1[] = "Hello, world!";
char s2[] = "everyone, ";
char *s_new = insert(s1, s2, 7);
printf("%s\n", s_new);
free(s_new);
return 0;
}
```
在这个函数中,首先计算出字符串s1和s2的长度,然后如果插入位置n超出了s1的范围,就返回原字符串s1并打印错误信息。接下来,使用malloc函数动态分配内存来创建一个新的字符串new_s,其长度为s1和s2的长度之和再加上1(为了放置字符串结束符'\0')。然后,使用strncpy函数将s1中位置0到n-1的子串复制到new_s中。接着,使用strncpy函数将s2复制到new_s的n位置处。最后,使用strncpy函数将s1中位置n到末尾的子串复制到new_s中,然后在new_s的末尾添加上'\0'。最后,释放原字符串s1所占用的内存空间,并返回新字符串new_s的指针。