[C++] 문자 배열의 5가지 순회 방법


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] << ' ';
}

2. 포인터 + while

이 방법은 문자 배열이 "\0"으로 끝나는 점을 활용합니다.

char *p = str;
while (*p != '\0')
{
    
    
    cout << *p << " ";
    p++;
}

3. 포인터 +

strlen을 기준으로 포인터가 증가해야 하는 횟수를 계산하려면 cstring 표준 라이브러리도 사용해야 합니다.

#include <cstring>

char *p2 = str;
for (int i = 0; i < strlen(str); i++)
{
    
    
    cout << *p2 << " ";
    p2++;
}

4. 포인터 + 아래첨자

cstring 표준 라이브러리를 사용하고 방법 1을 비교하면 포인터가 배열 이름과 동등한 것으로 간주될 수 있습니다.

char *p3 = str;
for (int i = 0; i < strlen(str); i++)
{
    
    
    cout << p3[i] << " ";
}

五、nullptr + while

순회가 널 포인터에 도달하면 중지합니다. 이 방법은 방법 2와 유사합니다.

// 方法五: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;
}

추천

출처blog.csdn.net/weixin_44844635/article/details/131742614