포스트

[C언어] 포인터로 문자열 거꾸로 출력

동아리 A반 5차 2일 과제

[동아리] A반 5차 2일 과제 (2024.03.20)


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
#include <stdio.h>
#include <string.h>

void reverse1(char *a) {
    for (int i=0;i<=strlen(a)/2;i++) {
        char temp = *(a+i);
        *(a+i) = *(a+strlen(a)-i-1);
        *(a+strlen(a)-i-1) = temp;
    }
}

void reverse2 (char *a) {
    int len = 0;
    int i = 0;
    while (*(a+i) != '\0') {
        i++;
        len++;
    }
  
    for (int i=0;i<=len/2;i++) {
        char temp = *(a+i);
        *(a+i) = *(a+len-i-1);
        *(a+len-i-1) = temp;
    }
}

int main() {
    char a[100] = "helloworld!";
    reverse1(a);
    printf("%s", a);
  
    printf("\n");
  
    char b[100] = "helloworld!";
    reverse2(b);
    printf("%s", b);

    return 0;
}

포인터를 사용해 대괄호 사용하지 않고 문자열 거꾸로 출력하기

sting.h 헤더파일을 사용하여 문자열의 길이 확인 후 주소값 계산에 활용 -  reverse1()
반복문을 통해서 문자열의 길이를 먼저 확인 후 주소값 계산에 활용 - reverse2()

이 게시글은 저작권자의 CC BY 4.0 라이센스를 따릅니다.