본문 바로가기
C 언어

C 언어 trim 함수 만들기 (1)

by treeCoder 2020. 11. 10.

 

C 언어에는 trim 함수가 없어서 직접 만들어서 사용하야 하기에 다음과 같이 trim 함수를 만들어 소개한다.

 

#include <stdio.h>

char *trim(char *a) {

    int i, c;

    for( c=0; a[c]==' ';c++ ); /* get the count of spaces */

    if( c != 0 ) {
        for( i = 0; a[i] = a[i+c]; i++);
    }
    
    for( i=0; a[i];i++ ); /* get the length */

    for( i = i-1; a[i] == ' '; i--); /* get the last non-space position */
    a[i+1] = 0x00; /* finish the string */

    return a;
}

int main() {

    char str[]="   Hello, Earth!   ";

    printf("Before trim: %s\n", str);
    trim(str);
    printf("After trim: %s\n", str);

    return 0;

}

 

onlinegdb.com 에서 실행 결과를 아래와 같이 확인할 수 있다.

 

 

'C 언어' 카테고리의 다른 글

C 언어 Rand 함수를 이용해서 무작위 암호 만들기  (0) 2020.12.16
C 언어에서 한 줄 읽어 들이기  (0) 2020.12.14
C strtok 함수  (1) 2020.11.19
C 키워드  (0) 2020.11.11
C 언어 코딩 헥사문자 들  (1) 2020.11.10

댓글