将代码中的*A和*B改为输入形式
时间: 2023-08-04 16:03:28 浏览: 45
好的,你可以按照下面的代码实现将字符串A和字符串B作为输入参数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
char *insert_string(char *A, char *B, int K, int M) {
int len_A = strlen(A);
int len_B = strlen(B);
if (len_A + len_B >= MAX_LEN) {
// 防止溢出
printf("Error: The length of the new string exceeds the maximum limit!\n");
return NULL;
}
if (K > len_A) {
// K超出A的范围
printf("Error: The insertion position K is out of range!\n");
return NULL;
}
// 将B插入到A中
memmove(A + K + len_B, A + K, len_A - K + 1);
memcpy(A + K, B, len_B);
return A;
}
int main() {
char A[MAX_LEN + 1];
char B[MAX_LEN + 1];
int K, M;
printf("Please enter string A: ");
fgets(A, MAX_LEN + 1, stdin);
A[strcspn(A, "\n")] = '\0'; // 去掉fgets读取的换行符
printf("Please enter string B: ");
fgets(B, MAX_LEN + 1, stdin);
B[strcspn(B, "\n")] = '\0'; // 去掉fgets读取的换行符
printf("Please enter the insertion position K: ");
scanf("%d", &K);
printf("Please enter the length of string B: ");
scanf("%d", &M);
char *result = insert_string(A, B, K, M);
if (result != NULL) {
printf("The new string is: %s\n", result);
}
return 0;
}
```
这样实现之后,用户可以在运行程序时输入字符串A、字符串B、插入位置K和字符串B的长度M,程序会将它们作为参数传递给`insert_string`函数,并输出新的字符串。需要注意的是,在使用`fgets`函数读取字符串时,需要去掉末尾的换行符,否则可能会影响后续的操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)