[英]C++ simple string program
初学者在这里
我用 C++ 写了下面的内容,这是一个短程序,目前以 2 个单词作为输入,并输出相同的单词,但单词被分成偶数和奇数。 我希望能够为“T”字做这件事,但我想不通。 我希望能够首先输入将要跟随的单词数,例如 10。然后输入单词并返回 T 结果。 因此,用户指定的数量不限,而不仅仅是 2 个词。
我需要将下面的内容放入一个函数中并在某个时候从那里开始,但我想学习最好的技术来做到这一点 - 请问有什么建议吗?
谢谢! 亚历克斯
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
string SecondWord;
cin >> SecondWord;
int LengthSecond;
LengthSecond = SecondWord.length();
string EvenSecond;
string OddSecond;
for (int i = 0; i < LengthSecond; i += 2){
EvenSecond += SecondWord[i];
}
for (int i = 1; i < LengthSecond; i += 2){
OddSecond += SecondWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
cout << EvenSecond << " " << OddSecond << endl;
return 0;
}
想我明白了,我想得太多了
我把它放在一个 for 循环中,如下所示 - 所以可以输入任意数量的单词,用户必须在
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <string> using namespace std; int main() { int T; cin >> T; for (int i = 0; i < T; i++){ string FirstWord; cin >> FirstWord; int LengthFirst; LengthFirst = FirstWord.length(); string EvenFirst; string OddFirst; for (int i = 0; i < LengthFirst; i += 2){ EvenFirst = EvenFirst + FirstWord[i]; } for (int i = 1; i < LengthFirst; i += 2){ OddFirst = OddFirst + FirstWord[i]; } cout << EvenFirst << " " << OddFirst << endl; } return 0; }
最终,您将执行N次相同的任务。
首先,让我们讨论如何存储信息。 从功能上讲,我们有一个字符串作为输入,它产生两个字符串作为输出。 std::pair
(来自<utility>
)让我们可以轻松地表示这一点。 但是为了奇偶, std::array
对我们来说可能是更好的表示。 由于我们有可变数量的单词作为输入,因此将输出可变数量的std::array
。 std::vector
(来自<vector>
)是我们的朋友。
其次,让我们讨论如何处理信息。 为每个输出组件使用命名变量不会缩放,所以让我们切换到一个固定数组(下面记为array<string,2>
。通过切换到一个固定数组进行输出,对每个拆分的寻址变成了循环索引( index % 2
). 下面是一个在编译时对已知分割大小进行概括的解决方案。
#include <string>
#include <array>
#include <vector>
#include <iostream>
int main() {
int N;
std::cin >> N;
constexpr const int Split = 2;
using StringPack = std::array<std::string, Split>;
std::vector<StringPack> output;
for (int wordIndex = 0; wordIndex < N; ++wordIndex) {
std::string word;
std::cin >> word;
StringPack out;
{
int index = 0;
for (char c : word) {
out[index % Split] += c;
++index;
}
}
output.emplace_back(out);
}
for (const auto & out : output) {
for (const auto & word : out) {
std::cout << word << ' ';
}
std::cout << '\n';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.