【C++】字符串遍历

一、下标遍历

#include <iostream>
#include <string>
using namespace std;

int main() {
	string str = "abcdefg";
	for (int i = 0; i < str.length(); i++) {
       cout<< str[i] <<endl; 
    }
    for (int i = 0; i < str.size(); i++) {
       cout<< str[i] <<endl; 
    }
    for (int i = 0; str[i] != '\0'; i++) {
       cout<< str[i] <<endl; 
    }
	return 0;
}

二、范围for语句

for(当前需要查找的遍历:需要遍历的容器)

常见范围 for 书写形式:
1、只读:for(const auto& 变量:需要遍历容器)
2、可读可写:for(auto& 变量:需要遍历的容器)

void stringTraverse() {
	string s = "123456";
	for (char ch : s) {
		cout << ch << endl;
	}
	for(auto c : s)
    {    
        cout << c; //范围for语句
    }

	// 只读
	for (const auto& ch : s) {
		cout << ch << endl;
	}
	// 可读可写
	for (auto& ch : s) {
		cout << ch << endl;
	}
}

三、迭代器 iterator

在这里插入图片描述
迭代的使用类似于指针,同样可以进行 解引用操作和自增操作。

(一)begin 接口与 end 接口

iterator begin(); const_iterator begin() const;
iterator end(); const_iterator end() const;

1、可读可写型

void stringTraverse() {
	string str1 = "12345";
	string::iterator it = str1.begin();
	while(it != str1.end()){
		cout << *it << " ";
		// 可以 *it = 'a';
		++it;
	}
	cout<<endl;

	for(auto iter = str.begin(); iter != str.end(); iter++) {
        cout << *iter; //迭代器访问
    }
    cout<<endl;
}

2、只读型

void stringTraverse() {
	string str2 = "12345";
	string::const_iterator it = str2.begin();
	while(it != str2.end()){
		cout << *it << " ";
		// 不可以 *it = 'a';
		++it;
	}
	cout<<endl;

	for(auto iter = str.begin(); iter != str.end(); iter++) {
        cout << *iter; //迭代器访问
    }
    cout<<endl;
}

(二)cbegin 接口与 cend 接口

const_iterator cbegin() const
const_iterator cend() const

可以看出来这两个接口都是被 const 修饰,因而cbegin / cend 都是只读迭代器,不可以修改其内容。

void stringTraverse() {
	const string str3 = "12345";
	string::const_iterator it3 = str3.cbegin();
	while (it3 != str3.cend()) {
		// 不可以 *i = 'a';
		cout << *it3 << "";
		++it3;
	}
	cout << end1;
}

(三)rbegin / rend 接口

rbegin 与 rend 是反向迭代器。
rbegin:指向最后一个元素的位置;
rend:指向第一个元素的前一个位置

reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;

void stringTraverse() {
	string str4 ="12345";
	string:reverse_iterator it4 = str4.rbegin();
	while (it4 != str4.rend()) {
		cout << *it4 << "";
		++it4;
	}
	cout << end1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值