当前位置:   article > 正文

【C++】字符数组 5 种遍历方法_c++ 字符串遍历

c++ 字符串遍历


C++中,如何实现遍历如下字符数组:

char str[] = {'z','i','f','u', 's', 'h', 'u', 'z', 'u'};
  • 1

一、数组 + 下标

注意,此方法使用了 strlen 函数,须引入 cstring 标准库:

#include <cstring>

for (int i = 0; i < strlen(str); i++)
{
    cout << str[i] << ' ';
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

二、指针 + while

此方法利用了字符数组以 “\0” 结束的特性:

char *p = str;
while (*p != '\0')
{
    cout << *p << " ";
    p++;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

三、指针 + for

根据 strlen 来计算指针需要自加的次数,同样需要用到 cstring 标准库:

#include <cstring>

char *p2 = str;
for (int i = 0; i < strlen(str); i++)
{
    cout << *p2 << " ";
    p2++;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

四、指针 + 下标

使用 cstring 标准库,对比方法一,此时指针可视作等同于数组名:

char *p3 = str;
for (int i = 0; i < strlen(str); i++)
{
    cout << p3[i] << " ";
}
  • 1
  • 2
  • 3
  • 4
  • 5

五、nullptr + while

当遍历到空指针时停止,此方法与方法二类似:

// 方法五:nullptr + while
char *p4 = str;
while (p4 != nullptr)
{
    cout << *p4 << " ";
    p4++;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

运行截图:
截图

附录:完整代码

#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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/398964
推荐阅读
相关标签
  

闽ICP备14008679号