C++遍历字符串

1. 常规方式

string s="hello"
for(int i=0;i<s.size();i++){
    cout<<s[i]<<"";
}

2.迭代器方式

begin接口 :         iterator begin();

end 接口:        iterator end();

循环方法

string s = "hello";
string::iterator it = s.begin();
while (it != s.end()) {
	cout << *it << "";
	++it;
}

3. 新for循环(C++11)

1.只读: for(const auto& 变量: 需要遍历的容器)

2.可读可写: for(auto &变量: 需要遍历的容器)

string s = "hello";
for (const auto& ch : s) {
	cout << c << "";//只读
}

for (auto& c : s) {
	c = 'a';// 可读可写
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ 中,如果字符串中包含中文字符,需要使用宽字符类型 `wchar_t` 或者多字节字符类型 `char` 来存储。在遍历字符串时,需要注意编码格式,避免出现乱码。 以下是一个遍历宽字符类型字符串的例子: ``` #include <iostream> #include <locale> #include <codecvt> int main() { std::wstring str = L"你好,世界!"; std::locale loc("zh_CN.UTF-8"); std::wcout.imbue(loc); std::wcout << str << std::endl; for (auto c : str) { std::wcout << c << std::endl; } return 0; } ``` 以上代码使用了 UTF-8 编码格式,可以正确输出中文字符。在遍历字符串时,使用 `auto` 关键字可以自动推断字符类型。注意,输出字符时需要使用 `std::wcout` 输出流。 如果使用的是多字节字符类型字符串,可以使用 `std::wstring_convert` 类进行转换: ``` #include <iostream> #include <locale> #include <codecvt> #include <string> int main() { std::string str = "你好,世界!"; std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; std::wstring wstr = converter.from_bytes(str); std::locale loc("zh_CN.UTF-8"); std::wcout.imbue(loc); std::wcout << wstr << std::endl; for (auto c : wstr) { std::wcout << c << std::endl; } return 0; } ``` 以上代码将多字节字符类型字符串转换为宽字符类型字符串,并且使用了 UTF-8 编码格式。在遍历字符串时,使用 `auto` 关键字可以自动推断字符类型。注意,输出字符时需要使用 `std::wcout` 输出流。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值