如何在 C++ 中遍歷字串
Jinku Hu
2023年1月30日
2020年11月24日
本文將介紹關於在 C++ 中如何在保持索引數的情況下對一個字串進行遍歷的多種方法。
在 C++ 中使用基於範圍的迴圈來遍歷一個字串
現代 C++ 語言風格推薦對於支援的結構,進行基於範圍的迭代。同時,當前的索引可以儲存在一個單獨的 size_t
型別的變數中,每次迭代都會遞增。注意,增量是用變數末尾的++
運算子來指定的,因為把它作為字首會產生一個以 1 開頭的索引。下面的例子只顯示了程式輸出的一小部分。
#include <iostream>
#include <string>
using std::cout; using std::cin;
using std::endl; using std::string;
int main(){
string text = "They talk of days for which they sit and wait";
size_t index = 0;
for (char c : text) {
cout << index++ << " - '" << c << "'" << endl;
}
return EXIT_SUCCESS;
}
輸出:
0 - 'T'
1 - 'h'
2 - 'e'
...
43 - 'i'
44 - 't'
在 C++ 中使用 for
迴圈遍歷字串
它在傳統的 for
迴圈中具有優雅和強大的功能,因為當內部範圍涉及矩陣/多維陣列操作時,它提供了靈活性。當使用高階並行化技術(如 OpenMP 標準)時,它也是首選的迭代語法。
#include <iostream>
#include <string>
using std::cout; using std::cin;
using std::endl; using std::string;
int main(){
string text = "They talk of days for which they sit and wait";
for (int i = 0; i < text.length(); ++i) {
cout << i << " - '" << text[i] << "'" << endl;
}
return EXIT_SUCCESS;
}
輸出:
0 - 'T'
1 - 'h'
2 - 'e'
...
43 - 'i'
44 - 't'
或者,我們可以使用 at()
成員函式訪問字串的單個字元。
#include <iostream>
#include <string>
using std::cout; using std::cin;
using std::endl; using std::string;
int main(){
string text = "They talk of days for which they sit and wait";
for (int i = 0; i < text.length(); ++i) {
cout << i << " - '" << text.at(i) << "'" << endl;
}
return EXIT_SUCCESS;
}
輸出:
0 - 'T'
1 - 'h'
2 - 'e'
...
43 - 'i'
44 - 't'
Author: Jinku Hu
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn