实现英文单词MyWord类,为该类提供各种功能(加法、流插入、流提取、查找、替换);
由于需要查找等功能,在其中利用了容器,便于查找单词;
1 #include<iostream>
2 #include<vector>
3 #include<algorithm>
4 #include<cstring>
5
6 using namespace std;
7
8 class MyWord
9 {
10 private:
11 string data;
12 int length;
13 public:
14 MyWord(string data_ = "NULL",int length_ = 0):data(data_),length(length_) { }
15 MyWord(const MyWord & rhs);
16 bool operator == (const MyWord & rhs)
17 { return data == rhs.data; }
18 MyWord operator + (const MyWord & rhs); // + 运算符
19 friend ostream & operator << (ostream & os ,const MyWord & rhs); // << 流插入
20 friend istream & operator >> (istream & is , MyWord & rhs); // >> 流提取
21 void Change(string str); // 替换
22 void Find(string str); // 查找
23 };
24
25 vector <MyWord> v; // MyWord 容器 v
26
27 MyWord::MyWord(const MyWord & rhs)
28 {
29 if(this != &rhs)
30 {
31 data = rhs.data;
32 length = rhs.length;
33 }
34 }
35
36 MyWord MyWord::operator + (const MyWord & rhs) // +运算符
37 {
38 return MyWord(data+rhs.data,rhs.length+length);
39 }
40
41 ostream & operator << (ostream & os ,const MyWord & rhs) // << 流插入
42 {
43 cout<<"data = "<<rhs.data<<" "<<rhs.length<<endl;
44 return (os);
45 }
46
47 istream & operator >> (istream & is , MyWord & rhs) // >> 流提取
48 {
49 is>>rhs.length>>rhs.data;
50 return (is);
51 }
52
53 void MyWord::Change(string str) // 替换
54 {
55 data = str;
56 }
57
58 void Find(string str) // 查找
59 {
60 MyWord virtu(str,str.length());
61 vector <MyWord>::iterator p;
62 p = find(v.begin(),v.end(),virtu);
63 if(p != v.end())
64 cout<<"找到该单词 :"<<*p<<endl;
65 else
66 cout<<"该单词不存在"<<endl;
67 }
68
69 int main()
70 {
71 int len,n,i = 0;
72 string da;
73 cout<<"输入单词时,请按照先输入字母个数,再输入单词的模式"<<endl;
74 cout<<"输入my 、 you "<<endl;
75 MyWord my,you,it;
76 cin>>my>>you;
77 cout<<"分别输出 my 与 you "<<endl<<my<<you; // 实现 << 与 >> 功能
78 it = my + you;
79 cout<<"it = my + you = "<<it; // 实现 + 功能
80 cout<<"输入替换单词"<<endl;
81 cin>>da;
82 it.Change(da);
83 cout<<"it 被替换 , it = "<<it; // 实现替换功能
84 cout<<"输入单词个数 :"<<endl; // 查找
85 cin>>n;
86 while(1)
87 {
88 cin>>it;
89 v.push_back( it );
90 if(++i == n)
91 break;
92 }
93 cout<<"请输入待查找单词 :"<<endl;
94 cin>>da;
95 Find(da); // 查找
96 return 0;
97 }
|
运行结果: 输入单词时,请按照先输入字母个数,再输入单词的模式 输入my 、 you 2 my 3 you 分别输出 my 与 you data = my 2 data = you 3 it = my + you = data = myyou 5 输入替换单词 hujun it 被替换 , it = data = hujun 5 输入单词个数 : 4 4 what 1 a 9 beautiful 3 day 请输入待查找单词 : beautiful 找到该单词 :data = beautiful 9 |
来源:https://www.cnblogs.com/2015-16/p/12180141.html