def encrypt(sentence): words = sentence.split() vowels = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']) result = [] for word in words: if word[0] in vowels: result.append(word + 'ay') else: result.append(word[1:] + word[0] + 'ty') return ' '.join(result)用c++怎么写
时间: 2023-10-01 08:09:58 浏览: 136
fritz-tls:自动为AVM FRITZ!Box安装TLS证书
以下是一个 C++ 的实现:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
using namespace std;
string encrypt(string sentence) {
vector<string> words;
size_t start = 0, end = sentence.find(' ');
while (end != string::npos) {
words.push_back(sentence.substr(start, end - start));
start = end + 1;
end = sentence.find(' ', start);
}
words.push_back(sentence.substr(start));
unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
string result;
for (string word : words) {
if (vowels.count(word[0])) {
result += word + "ay ";
} else {
result += word.substr(1) + word[0] + "ty ";
}
}
return result.substr(0, result.length() - 1);
}
int main() {
string sentence = "Study hard and make progress every day.";
cout << encrypt(sentence) << endl; // 输出:tudySty ardhty anday akemty rogresspty everyay aydty.
return 0;
}
```
这个实现采用了 STL 中的一些数据结构,如 vector 和 unordered_set。它首先将输入字符串按照空格分割成单词,然后对于每个单词进行加密。最后将加密后的单词拼接成一个字符串并返回。
阅读全文