題目1:
輸入壹批字符串(不超過30條),以字符串“end”作為輸入結束標誌,請按要求編程完成下述功能:
1)字符串輸入;
2)輸出最大、最小的字符串及其位置;
3)對字符串進行升序排列;
4)插入壹條字符串,結果仍按升序排列;
5)查找指定字符串的位置;
6)刪除指定的字符串。
要求:
1)上述各功能請分別用函數實現;
2)輸入輸出要有必要的提示說明
*/
#include <iostream>
#include<string>
#include<stdlib.h>
using namespace std;
void input();//字符串輸入
void outputMaxMinAndItsLocation();//輸出最大、最小的字符串及其位置
void orderByAesc();//對字符串進行升序排列
void insertString();//插入壹條字符串,結果仍按升序排列
bool selectString();//查找指定字符串的位置
void deleteString();//刪除指定的字符串
void print(); //輸出所有字符串
string str[30];//定義壹個不超過30個字符串的字符串數組
int size=0;
void input()
{
size=0;
int i=0;
cout<<endl<<"輸入字符串,以輸入'end'結束:"<<endl;
while(i<30)
{
cout<<"字符串"<<i+1<<":";
cin>>str[i];
if(str[i]=="end")
{
break;
}
size++;
i++;
}
}
void outputMaxMinAndItsLocation()
{
string max=str[0],min=str[0];
int maxLocation=0,minLocation=0;
int i=1;
while(i<size)
{
if(min.length()>str[i].length())
{
min=str[i];
minLocation=i;
}
else if(max.length()<str[i].length())
{
max=str[i];
maxLocation=i;
}
i++;
}
cout<<endl<<"最大字符串:"<<max<<" "<<"位置:"<<maxLocation<<endl;
cout<<"最小字符串:"<<min<<" "<<"位置:"<<minLocation<<endl;
}
void orderByAesc()
{
string temp;
for(int i=0;i<size;i++)
for(int j=i+1;j<size;j++)
{
temp=str[i];
if(str[i]>str[j])
{
str[i]=str[j];
str[j]=temp;
}
}
}
void insertString()
{
string temp;
cout<<"請輸入想要插入的字符串:";
cin>>temp;
str[size]=temp;
size++;
orderByAesc();//升序排序
}
bool selectString()
{
cout<<"請輸入想要查找的字符串:";
string temp;
cin>>temp;
for(int i=0;i<size;i++)
{
if(str[i]==temp)
{
cout<<"存在該字符串,位於"<<i<<endl;
return true;
}
else if(i==size-1)
{
cout<<"不存在該字符串"<<endl;
}
}
return false;
}
void deleteString()
{
cout<<"請輸入想要刪除的字符串:";
string temp;
cin>>temp;
for(int i=0;i<size;i++)
{
if(str[i]==temp)
{
for(int j=i;j<size;j++)
str[j]=str[j+1];
size--;
}
}
}
void print()
{
cout<<endl<<"輸出所有字符串!!"<<endl<<endl;
for(int i=0;i<size;i++)
cout<<"字符串"<<i+1<<":"<<str[i]<<endl;
cout<<endl<<"輸出完畢!!"<<endl<<endl;
}
int main()
{
int choice;
while(1)
{
cout<<endl<<"*********************************************"<<endl;
cout<<"\t1:輸入字符串"<<endl;
cout<<"\t2:輸出最大、最小的字符串及其位置"<<endl;
cout<<"\t3:對字符串進行升序排列"<<endl;
cout<<"\t4:插入壹條字符串,結果仍按升序排列"<<endl;
cout<<"\t5:查找指定字符串的位置"<<endl;
cout<<"\t6:刪除指定的字符串"<<endl;
cout<<"\t7:輸出所有字符串"<<endl;
cout<<"\t0:退出"<<endl;
cout<<"*********************************************"<<endl;
cout<<"請輸入妳要進行的操作:";
cin>>choice;
switch(choice)
{
case 0:cout<<"退出!!"<<endl;exit(0);break;
case 1:input();break;
case 2:outputMaxMinAndItsLocation();break;
case 3:orderByAesc();cout<<"升序排序完畢"<<endl;break;
case 4:insertString();break;
case 5:selectString();break;
case 6:deleteString();break;
case 7:print();break;
default:cout<<"輸入錯誤!!!"<<endl;
}
}
return 0;
}