프로그래밍/C,C++

[C] 문자열함수 trim,ltrim,rtrim,split 만들기

ss-pro 2020. 9. 27. 00:29
반응형

C언어상에서는 문자열관련 함수가 제한적이기 때문에공백문자제거함수인Trim,Rtrim,Ltrim 함수가 없기때문에 만들어서 사용해보록 하겠습니다. 

1. ltrim함수 구현방법
문자열 처음부터 검색해서 스페이스값이 나올때까지 반복실행하다가 스페이스값이 나오면 해당부분 포인터 위치를 옮기면됩니다.

2. rtrim함수 구현방법 
ltrim과 반대로 문자열의 마지막부분부터 역순으로 스페이스값이 나올때까지 반복하다가 스페이스가 있으면 문자열종료를 알려주는  *(end + 1= '\\0'  값을 할당해주면됩니다. 

3. trim 
ltrim, rtrim을 한번씩해주면됩니다. 


스페이스 유무를 체크해보려면 isspace()함수를 사용해야합니다. Man Page를 검색해서 확인하면 프로토타입을 확인해보겠습니다. 
#include <ctype.h>
int isalnum(int c); int isalpha(int c); int isascii(int c); int isblank(int c); int iscntrl(int c); int isdigit(int c); int isgraph(int c); int islower(int c); int isprint(int c); int ispunct(int c); int isspace(int c); int isupper(int c); int isxdigit(int c);

isspace()
checks for white-space characters. In the "C" and "POSIX" locales, these are: space, form-feed ('\\f'), newline ('\\n'), carriage return ('\\r'), horizontal tab ('\\t'), and vertical tab ('\\v').isupper()checks for an uppercase letter.isxdigit()checks for a hexadecimal digits, that is, one of
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
.

Return Value

The values returned are nonzero if the character c falls into the tested class, and a zero value if not.
(공백과 관련된 문자값일경우에는 0아닌값을 리턴, 그외에는 0을 리턴함)

전체소스코드 
mstr.h 전체코드 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef __MSTR_H_
#define __MSTR_H_
#include <ctype.h>
/* string left trim
 *
 * */
char *mstr_ltrim(char *s);
/* string right trim
 * param : s ,  max length = 4000 byte
 * */
char *mstr_rtrim(char *s);
/* string trim 
 * param : s ,  max length = 4000 byte
 * */
char *mstr_trim(char *s);
int mstr_split(char *dst[],char *src,const char *delim);
#endif

 

mstr.c 전체코드

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
#include <string.h>
#include "mstr.h"
 
extern char* mstr_ltrim(char *s) {
    char* begin;
    begin = s;
    while (*begin != '\0'
    {
        if (isspace(*begin))
            begin++;
        else {
            s = begin;
            break;
        }
    }
    return s;
}
 
extern char* mstr_rtrim(char* s) {
    char t[4000];
    char *end;
    strcpy(t, s);
    end = t + strlen(t) - 1;
    while (end != t && isspace(*end))
    {
        end--;
    }
    *(end + 1= '\0';
    s = t;
    return s;
}
 
extern char* mstr_trim(char *s) {
    return mstr_rtrim(mstr_ltrim(s));
}
 
extern int mstr_split(char *dst[],char *src,const char *delim)
{
    char *p;
    int cnt=0;
 
    p = strtok(src,delim);
    while (p!=NULL)
    {
        dst[cnt]=p;
        cnt++;
        p = strtok(NULL,delim);    
    }
 
    return cnt;
}

 
 

cs

 

 

 

참고)
linux.die.net/man/3/isspace

반응형