C++中,如何实现遍历如下字符数组:
char str[] = {'z','i','f','u', 's', 'h', 'u', 'z', 'u'};
一、数组 + 下标
注意,此方法使用了 strlen 函数,须引入 cstring 标准库:
#include <cstring>
for (int i = 0; i < strlen(str); i++)
{
cout << str[i] << ' ';
}
二、指针 + while
此方法利用了字符数组以 “\0” 结束的特性:
char *p = str;
while (*p != '\0')
{
cout << *p << " ";
p++;
}
三、指针 + for
根据 strlen 来计算指针需要自加的次数,同样需要用到 cstring 标准库:
#include <cstring>
char *p2 = str;
for (int i = 0; i < strlen(str); i++)
{
cout << *p2 << " ";
p2++;
}
四、指针 + 下标
使用 cstring 标准库,对比方法一,此时指针可视作等同于数组名:
char *p3 = str;
for (int i = 0; i < strlen(str); i++)
{
cout << p3[i] << " ";
}
五、nullptr + while
当遍历到空指针时停止,此方法与方法二类似:
// 方法五:nullptr + while
char *p4 = str;
while (p4 != nullptr)
{
cout << *p4 << " ";
p4++;
}
运行截图:
附录:完整代码
#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;
}