计算机考研复试上机题 —— 单词替换 (北京大学)

 

 

思路:

  1. 通过分割标志,将整句话分割成多个单词;

  2. 将指定的单词替换内容,输出替换后的句子;

C++代码:

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 
 5 using namespace std;
 6 
 7 vector<string> list; 
 8 string str, temp;
 9 
10 
11 //通过空格分割单词 
12 void splitString() {
13     //start:单词起点, span:单词长度 
14     int start, span, length;
15     start = span = 0;
16     length = str.length();
17     for(int i=0; i<length; i++) {
18         if(str[i] == ' ') {
19             //substr(起始下标, 截取长度) 
20             temp = str.substr(start, span);
21             list.push_back(temp);
22             start = i+1;
23             //置零 
24             span = 0;
25             continue;
26         }
27         //处理最后一个单词 
28         if(i == length-1) {
29             //留意最后一个单词的长度 
30             temp = str.substr(start, span+1);
31             list.push_back(temp);
32         }
33         span++;
34     }
35     
36 }
37 
38 
39 void solve() {
40     int listLen;
41     string origin, replace;
42     //通过回车结束字符串而不是空格 
43     getline(cin, str);
44     //分割单词 
45     splitString();
46     cin>> origin>> replace;
47     listLen = list.size();
48     for(int i=0; i<listLen; i++) {
49         temp = list[i];
50         //替换指定单词的内容 
51         if(temp == origin) {
52             list[i] = replace;
53         }
54     }
55     //打印单词结果 
56     for(int i=0; i<listLen; i++) {
57         if(i != 0) {
58             cout<< " ";
59         }
60         cout<< list[i];
61     }
62     cout<< endl;
63 }
64 
65 
66 int main() {
67     solve();
68     
69     return 0;
70 }

猜你喜欢

转载自www.cnblogs.com/Lunix-touch/p/12322292.html