#include <iostream>
#include <cstring>
using namespace std;
void DataInput(char ** a); // 资料输入模块
int DataSearch(char * a, char ** b); // 单词查找模块
void DataReplace(char * a, char * b, char ** c, int d); // 单词替换模块
void DataShow(char ** a); // 资料查看模块
int number; // 储存的单词总数
int main()
{
int key; // 用一个数字控制各种功能
int n; // 替换或删除的单词个数
char * word1 = new char[50]; // 查找的单词
char * word2 = new char[50]; // 替换的单词
cout << "请输入储存的单词个数:";
cin >> number; // ********此处输入字母会死机********可以加入检测输入功能加以完善
char ** p = new char *[number]; // 二维指针指向存储的数据
for (int i = 0; i < number; ++i)
p[i]= new char[50]; // 每个单词的最大长度为
DataInput(p);
while (key != 5) // key 为5 时退出程序
{
cout << "请选择操作:/n" << "(1) 全部替换; (2) 全部删除; (3) 查找; (4) 查看当前状态; (5) 退出;/n";
cin >> key;
if (key == 1)
{
cout << "需要全部替换为: ";
cin >> word2;
while (cin.get() != '/n') // 避免一行输入多个空格导致的输入跳跃
;
for (int i = 0; i < number; ++i)
strcpy(p[i], word2);
cout << "/n全部替换完成!/n/n";
}
else if (key == 2)
{
cout << "是否要全部删除?输入Y 确定,其它任意键取消 ";
char temp;
cin >> temp;
while (cin.get() != '/n')
;
if (temp == 'y' || temp == 'Y')
{
strcpy(word2, "");
for (int i = 0; i < number; ++i)
strcpy(p[i], word2);
cout << "/n全部删除完成!/n";
}
cout << endl;
}
else if (key == 3)
{
while (key == 3) // 查找之后再次查找的循环
{
cout << "请输入要查找的单词:";
cin >> word1;
int result = DataSearch(word1, p);
cout << "/n共查找到" << result << " 个相同单词/n/n";
if (result != 0)
{
cout << "请选择操作:/n" << "(1) 替换; (2) 删除; (3) 查找; (4) 查看当前状态; (5) 退出;/n";
cin >> key;
if (key == 1)
{
cout << "/n要替换几处?";
cin >> n;
while (n > result)
{
cout << "输入错误,当前只查找到" << result << " 个可替换单词,请重新输入:";
cin >> n;
while (cin.get() != '/n')
;
}
cout << "/n要替换为:";
cin >> word2;
while (cin.get() != '/n')
;
DataReplace(word1, word2, p, n);
}
else if (key == 2)
{
cout << "/n要删除几处?";
cin >> n;
while (n > result)
{
cout << "/n输入错误,当前只查找到" << result << " 个可删除单词,请重新输入:";
cin >> n;
while (cin.get() != '/n')
;
}
strcpy(word2, "");
DataReplace(word1, word2, p, n);
}
else if (key == 3)
key = 3; // 继续查找
else if (key == 4)
{
cout << "/n当前存储的数据如下:/n";
DataShow(p);
}
else if (key == 5)
key = 5; // 退出系统
}
else // 查找结果为,跳出循环
break;
}
}
else if (key == 4)
{
cout << "/n当前存储的数据如下:/n";
DataShow(p);
}
else if (key == 5)
key = 5; // 退出系统
}
cout << "/n/n程序结束,谢谢使用!^O^/n";
delete [] word1;
delete [] word2;
delete [] p;
return 0;
}
void DataInput(char ** a)
{
cout << "/n逐个输入单词:/n";
for (int i = 0; i < number; ++i)
{
cout << "#" << i + 1 << ": ";
cin >> a[i];
while (cin.get() != '/n') // 避免一行输入多个空格导致的输入跳跃
;
}
cout << "/n单词输入完毕!/n/n";
}
int DataSearch(char * a, char ** b)
{
int count = 0; // 记录符合查找要求的单词个数
for (int i = 0; i < number; ++i)
{
if (strcmp(a, b[i]) == 0)
count++;
}
return count;
}
void DataReplace(char * a, char * b, char ** c, int d)
{
int temp = d; // 统计替换个数
for (int i = 0; i < number; ++i)
{
if (strcmp(a, c[i]) == 0)
{
strcpy(c[i], b);
temp--;
}
if (temp == 0)
break;
}
cout << "/n操作完成!/n/n";
}
void DataShow(char ** a)
{
for (int i = 0; i < number; ++i)
{
cout << a[i] <<" ";
if ((i+1) % 5 == 0)
cout << endl;
}
cout << endl;
}