R. *_*des 385
通过循环字符的std::string,使用范围为基础的环路(它从C++ 11的,已经支持在最近GCC,铛和VC11的β版本):
std::string str = ???;
for(char& c : str) {
do_things_with(c);
}
Run Code Online (Sandbox Code Playgroud)循环遍历std::string带有迭代器的字符:
std::string str = ???;
for(std::string::iterator it = str.begin(); it != str.end(); ++it) {
do_things_with(*it);
}
Run Code Online (Sandbox Code Playgroud)循环std::string使用旧式for 循环的字符:
std::string str = ???;
for(std::string::size_type i = 0; i < str.size(); ++i) {
do_things_with(str[i]);
}
Run Code Online (Sandbox Code Playgroud)循环遍历以null结尾的字符数组的字符:
char* str = ???;
for(char* it = str; *it; ++it) {
do_things_with(*it);
}
Run Code Online (Sandbox Code Playgroud)小智 28
for循环可以像这样实现:
string str("HELLO");
for (int i = 0; i < str.size(); i++){
cout << str[i];
}
Run Code Online (Sandbox Code Playgroud)
这将按字符打印字符串.str[i]返回索引处的字符i.
如果是字符数组:
char str[6] = "hello";
for (int i = 0; str[i] != '\0'; i++){
cout << str[i];
}
Run Code Online (Sandbox Code Playgroud)
基本上上面两个是c ++支持的两种类型的字符串.第二个叫做c string,第一个叫做std string或(c ++ string).我建议用c ++ string,很容易处理.
Ker*_* SB 24
在现代C++中:
std::string s("Hello world");
for (char & c : s)
{
std::cout << "One character: " << c << "\n";
c = '*';
}
Run Code Online (Sandbox Code Playgroud)
在C++ 98/03中:
for (std::string::iterator it = s.begin(), end = s.end(); it != end; ++it)
{
std::cout << "One character: " << *it << "\n";
*it = '*';
}
Run Code Online (Sandbox Code Playgroud)
对于只读迭代,您可以std::string::const_iterator在C++ 98中使用,for (char const & c : s)或者for (char c : s)在C++ 11中使用.
0xB*_*F00 11
这是另一种使用标准算法的方法.
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string name = "some string";
std::for_each(name.begin(), name.end(), [] (char c) {
std::cout << c;
});
}
Run Code Online (Sandbox Code Playgroud)
const char* str = "abcde";
int len = strlen(str);
for (int i = 0; i < len; i++)
{
char chr = str[i];
//do something....
}
Run Code Online (Sandbox Code Playgroud)
我没有看到任何使用基于范围的带有“c 字符串”的 for 循环的示例。
char cs[] = "This is a c string\u0031 \x32 3";
// range based for loop does not print '\n'
for (char& c : cs) {
printf("%c", c);
}
Run Code Online (Sandbox Code Playgroud)
不相关但 int 数组示例
int ia[] = {1,2,3,4,5,6};
for (int& i : ia) {
printf("%d", i);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
374609 次 |
| 最近记录: |