[英]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.