溫馨提示×

c++如何讀取字符串中的某個字符

c++
小億
423
2024-04-11 19:10:05
欄目: 編程語言

可以使用下標或者迭代器來訪問字符串中的某個字符。下面是兩種方法:

  1. 使用下標:
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";
    
    char ch = str[4]; // 通過下標訪問字符串中的第5個字符,索引從0開始
    std::cout << "The fifth character is: " << ch << std::endl;
    
    return 0;
}
  1. 使用迭代器:
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";
    
    std::string::iterator it = str.begin();
    std::advance(it, 7); // 移動迭代器到第8個字符的位置
    
    char ch = *it; // 通過迭代器訪問第8個字符
    std::cout << "The eighth character is: " << ch << std::endl;
    
    return 0;
}

以上兩種方法都可以用來訪問字符串中的指定字符,根據具體需求選擇適合的方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女