首頁 >後端開發 >C++ >如何迭代 C 字串中的字元?

如何迭代 C 字串中的字元?

Linda Hamilton
Linda Hamilton原創
2024-11-30 10:37:08996瀏覽

How Can I Iterate Through Characters in a C   String?

在 C 語言中循環字串中的字元

迭代字串中的字元是程式設計中的常見任務。以下是在C 中實現此目的的不同方法:

基於範圍的For 循環(C 11 及以上)

std::string str = ???;
for (char& c : str) {
    // Perform actions on the character 'c'
}

基於迭代器的For循環

std::string str = ???;
for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
    // Perform actions on the character '*it'
}

傳統For循環

std::string str = ???;
for (std::string::size_type i = 0; i < str.size(); ++i) {
    // Perform actions on the character 'str[i]'
}

空終止字元陣列循環

For C 風格以 null 結尾的字串,使用:

char* str = ???;
for (char* it = str; *it; ++it) {
    // Perform actions on the character '*it'
}

以上是如何迭代 C 字串中的字元?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn