赞
踩
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] << ' ';
}
此方法利用了字符数组以 “\0” 结束的特性:
char *p = str;
while (*p != '\0')
{
cout << *p << " ";
p++;
}
根据 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
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; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。