【C++大作业】26.字符串的处理

问题描述:
设有若干个字符串,这些字符串存储位置的首地址保存在指针数组中(即字符串用指向字符的指针变量表示)。

实现要求:
⑴ 实现字符串的输入和输出;
⑵ 对所有的字符串按从小到大的顺序排序,即指针数组中的第一个元素指向最小的字符串,第二个元素指向次小的字符串…,依次类推;
⑶ 判断这些字符串中是否有“回文”,所谓“回文”指的是顺读和倒读都是一样的字符串;
⑷ 设计一个菜单,具有上述规定的操作要求、退出系统等最基本的功能。

#include<iostream>
#include<string.h>
#include<string>
using namespace std;
int  main(){
    
    
	void input(char *p[],int n);
	void print(char *p[],int n);
	void sort(char *p[],int n);
	bool isPalindrome(const char *str);
	void printPalindrome(char *p[],int n);
	int n;
	char number; 
	char *p[100];//声明指针数组长度 
	cout<<"#---字符串处理---#\n";
	cout<<"1.输入字符串\n";
	cout<<"2.排序后输出\n";
	cout<<"3.输出回文\n";
	cout<<"4.退出\n";
	while(true){
    
    
		cout<<"请输入选项序号:";
		cin>>number;
		switch(number){
    
    
			case '1':
				cout<<"请输入指针数组长度:";
				cin>>n;
				input(p,n);
				break;
			case '2':
				cout<<"排序后的指针数组:\n"; 
				sort(p,n);
				print(p,n);
				break;
			case '3':
				cout<<"输出该数组的回文字符串:\n";
				printPalindrome(p,n);
				break;
			case '4':
				cout<<"退出系统\n";
				return 0;
				break;
			default:
				cout<<"输入选项序号错误\n"; 
				break; 					
		}
	} 
return 0;	
}
void input(char *p[],int n){
    
      //输入 
	for(int i=0;i<n;i++){
    
    
		p[i] = new char[20];//申请内存 
		cin>>p[i];		
	}
}
void print(char *p[],int n){
    
      //打印 
	for(int i=0;i<n;i++){
    
    
		cout<<p[i]<<"\n";
	}
}
void sort(char *p[],int n){
    
      //排序 
	char *temp;
	for(int i=0;i<n;i++){
    
    
		for(int j=i+1;j<n;j++){
    
    
			if(strcmp(p[i],p[j]) > 0){
    
    
				temp = p[i];
				p[i] = p[j];
				p[j] = temp;
			}
		}
	}
}
bool isPalindrome(const char *str){
    
     // 判断回文
	int len = strlen(str);
	for(int i=0;i<len/2;i++){
    
    
		if(str[i] != str[len-i-1])
			return false;
	}
	return true;
}
void printPalindrome(char *p[],int n){
    
     //输出回文 
	bool flag = true;
	for(int i=0;i<n;i++){
    
    
		if(isPalindrome(p[i])){
    
    
			flag = false;
			cout<<p[i]<<"\n";
		}	
	}
	if(flag)
		cout<<"该数组无回文字符串\n";
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_48180029/article/details/111999651
今日推荐