Summary of methods
In C++, how to traverse the following character array:
char str[] = {
'z','i','f','u', 's', 'h', 'u', 'z', 'u'};
1. Array + subscript
Note that this method uses the strlen function and must introduce the cstring standard library:
#include <cstring>
for (int i = 0; i < strlen(str); i++)
{
cout << str[i] << ' ';
}
2. Pointer + while
This method takes advantage of the fact that character arrays end with "\0":
char *p = str;
while (*p != '\0')
{
cout << *p << " ";
p++;
}
3. Pointer + for
To calculate the number of times a pointer needs to be incremented based on strlen, you also need to use the cstring standard library:
#include <cstring>
char *p2 = str;
for (int i = 0; i < strlen(str); i++)
{
cout << *p2 << " ";
p2++;
}
4. Pointer + subscript
Using the cstring standard library and comparing method 1, the pointer can be regarded as equivalent to the array name:
char *p3 = str;
for (int i = 0; i < strlen(str); i++)
{
cout << p3[i] << " ";
}
五、nullptr + while
Stop when the traversal reaches the null pointer. This method is similar to method 2:
// 方法五:nullptr + while
char *p4 = str;
while (p4 != nullptr)
{
cout << *p4 << " ";
p4++;
}
Running screenshot:
Appendix: Complete code
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[] = {
'z', 'i', 'f', 'u', 's', 'h', 'u', 'z', 'u'};
// 方法一:数组 + 下标
cout << "method1:";
for (int i = 0; i < strlen(str); i++)
{
cout << str[i] << ' ';
}
// 方法二:指针 + while
cout << endl
<< "method2:";
char *p1 = str;
while (*p1 != '\0')
{
cout << *p1 << " ";
p1++;
}
// 方法三:指针 + for
cout << endl
<< "method3:";
char *p2 = str;
for (int i = 0; i < strlen(str); i++)
{
cout << *p2 << " ";
p2++;
}
// 方法四:指针 + 下标
cout << endl
<< "method4:";
char *p3 = str;
for (int i = 0; i < strlen(str); i++)
{
cout << p3[i] << " ";
}
// 方法五:nullptr + while
cout << endl
<< "method5:";
char *p4 = str;
while (p4 != nullptr)
{
cout << *p4 << " ";
p4++;
}
return 0;
}