C++2) 从键盘输入字符串a和字符串b,并在a串中的最小元素(不含结束符)后面插入字符串b。
时间: 2024-05-06 22:20:09 浏览: 16
```c
#include <stdio.h>
#include <string.h>
int main() {
char a[100], b[100];
printf("请输入字符串a:");
gets(a);
printf("请输入字符串b:");
gets(b);
int len_a = strlen(a);
int min_index = 0;
for (int i = 1; i < len_a; i++) {
if (a[i] < a[min_index]) {
min_index = i;
}
}
// 将b插入到a串的最小元素后面
for (int i = len_a; i >= min_index + 1; i--) {
a[i + strlen(b)] = a[i];
}
for (int i = 0; i < strlen(b); i++) {
a[min_index + 1 + i] = b[i];
}
printf("插入后的字符串a:%s", a);
return 0;
}
```
运行示例:
```
请输入字符串a:apple
请输入字符串b:orange
插入后的字符串a:aporangeple
```
相关问题
用c++编程从键盘输入字符串a和字符串b,并在a串中的最小元素(不含结束符)后面插入字符串b
请看下面的代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char a[100], b[100];
printf("请输入字符串a:");
fgets(a, 100, stdin); // 从键盘读入字符串a
printf("请输入字符串b:");
fgets(b, 100, stdin); // 从键盘读入字符串b
int min_idx = 0;
for (int i = 1; i < strlen(a); i++) {
if (a[i] < a[min_idx])
min_idx = i; // 找到最小元素的下标
}
for (int i = strlen(a) - 1; i >= min_idx; i--) {
a[i + strlen(b)] = a[i];
}
for (int i = 0; i < strlen(b); i++) {
a[min_idx + i + 1] = b[i];
}
printf("插入后的字符串a:");
puts(a); // 输出字符串a
return 0;
}
```
这段代码会先让你从键盘输入字符串a和字符串b,然后找到字符串a中最小的元素(不含结束符)的下标,再将字符串b插入到这个最小元素后面。最后输出插入后的字符串a。
注意,如果字符串a的长度已经等于100,这段代码会溢出导致程序崩溃。本代码未进行异常处理,使用时需要注意。
从键盘输入字符串a和字符串b,并在a串中的最小元素(不含结束符)后面
插入字符串b,可以使用如下的C++代码实现:
```
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[100], b[100];
cout << "请输入字符串a:" << endl;
cin >> a;
cout << "请输入字符串b:" << endl;
cin >> b;
int len_a = strlen(a);
if (len_a == 0) {
strcpy(a, b);
} else {
int min_idx = 0;
for (int i = 1; i < len_a; i++) {
if (a[i] < a[min_idx]) {
min_idx = i;
}
}
char temp[100];
strcpy(temp, a + min_idx + 1);
a[min_idx + 1] = '\0';
strcat(a, b);
strcat(a, temp);
}
cout << "插入后的字符串为:" << a << endl;
return 0;
}
```
首先从键盘输入字符串a和字符串b,然后找到a串中的最小元素的位置min_idx。接着,将a串中min_idx+1位置之后的字符拷贝到临时数组temp中,并将a串中min_idx+1位置设置为结束符'\0'。然后将字符串b拼接到a串中,并再次拼接temp数组中的字符。最后输出插入后的字符串a。
相关推荐
![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)
![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)