以下数组实现输入5个字符串,对这5个字符串排序,例如输入:
China
Japan
India
Italy
Korea
#include<iostream>
using namespace std;
void main()
{
//这里不能定义字符数组的第二维长度为5,因为元素之间需要间隔,否则编译系统无法区分元素之间的起始位置
//str[0]指向的内容会变成”ChinaJapanIndiaItalyKorea“
//所以字符数组定义的长度应该略大于实际存放的数据长度,不能刚刚相等
//char str[5][5], temp[5], *pt=temp;
char str[5][6], temp[5], *pt=temp;
int i,j;
cout<<"please input 5 strings:"<<endl;
for(i=0; i < 5; i++)
cin>>str[i];
/*for(i=0; i < 5; i++) //当运行是错误,可以尝试输出相应的信息观察
cout<<str[i]<<" "; */
cout<<endl;
cout<<"sorted strings:"<<endl;
cout<<endl;
for(i=0; i < 4; i++)
//for(j=0; j < 5 - i; j++)
//注意以下的判定条件应该是”j < 5 - i“不是"j < 6 - i"否则当j == 5是str[i+1]则是str[6]下标越界
for(j=0; j < 5 - i; j++)
if(strcmp(str[j], str[j + 1]) > 0)
{ strcpy(pt, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], pt);
}
for(i=0; i < 5; i++)
cout<<str[i]<<endl;
}
本文介绍了一个使用C++实现的字符串数组排序程序实例。该程序能够接收用户输入的5个字符串,并利用选择排序算法对这些字符串进行升序排列。通过这个例子,读者可以学习如何在C++中处理字符串数组及实现基本的排序逻辑。

被折叠的 条评论
为什么被折叠?



