c++如何读取字符串中的某个字符

c++
581
2024/4/23 19:10:05
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

可以使用下标或者迭代器来访问字符串中的某个字符。下面是两种方法:

  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;
}

以上两种方法都可以用来访问字符串中的指定字符,根据具体需求选择适合的方法。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++选择语句怎么使用