从键盘上随机输入6个字符串,要求按字典中的顺序输出。【输入形式】
从键盘上随机输入6个字符串【输出形
式】
按字典中的顺序输出6个字符串【样例输入】
hello
tourist
passport
Customs
officer
friend
【样例输出】customs 4
friend
hello
officer
passport
tourist
参考如下
#include <stdio.h>
#include <string.h>
int main(){
char a[6][100] = {'\0'};
int i,j;
for (i = 0; i < 6; i++){
scanf("%s", a[i]);
getchar();
}
char t[7];
for(i=0;i<5;i++)
for(j=0;j<5-i;j++)
if(strcmp(a[j],a[j+1])>0)
{
strcpy(t,a[j]);
strcpy(a[j],a[j+1]);
strcpy(a[j+1],t);
}
for(i=0;i<6;i++)
printf("%s\n",a[i]);
return 0;
}
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> strings;
// 从键盘上输入 6 个字符串
for (int i = 0; i < 6; ++i) {
std::string s;
std::cin >> s;
strings.push_back(s);
}
// 将字符串按字典序排序
std::sort(strings.begin(), strings.end());
// 输出排序后的字符串
for (const auto& s : strings) {
std::cout << s << std::endl;
}
return 0;
}
问题解答:
通过以上参考资料,我们无法直接得到解决本问题的方案。本问题需要自己编写程序来实现从键盘上随机输入6个字符串,并按字典顺序输出这些字符串。下面是一个可能的解决方案:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// 创建长度为6的字符串数组
string str[6];
// 循环输入6个字符串
cout << "请依次输入6个字符串:" << endl;
for (int i = 0; i < 6; i++) {
cin >> str[i];
}
// 对字符串进行排序
sort(str, str+6);
// 输出排过序的字符串
cout << "排序后的字符串为:" << endl;
for (int i = 0; i < 6; i++) {
cout << str[i] << endl;
}
return 0;
}
代码说明:
首先创建一个长度为6的字符串数组,用来存储用户输入的6个字符串。
然后循环输入6个字符串,通过cin
函数实现。
接着使用std::sort
函数对字符串数组进行排序,按字典顺序从小到大排序。
最后循环输出排过序的6个字符串,通过cout
函数实现。
需要注意的是,该代码对输入字符串是否区分大小写没有进行处理,默认按照ASCII码进行排序。如果需要区分大小写可以使用std::transform
函数将字符串全部转化成小写或大写字母再进行排序。
样例输入:
hello world apple book cat dog Flower
样例输出:
排序后的字符串为: Flower apple book cat dog hello