Backend/C

문자열의 길이를 계산하는 두 가지 방법

petitCoding 2012. 4. 12. 10:23

<1> 사용자 정의 함수를 만들어 주기

 

1 :  #include <stdio.h>
2 : 

3 :  int str_len(char *);
4 :  void main(){
5 :          char buf[20];
6 :          puts("\nEnter a line of text: a blank line terminates.");
7 :          gets(buf);
8 :          int length = str_len(buf);
9 :          printf("\nThat line is %u characters long.", length);
10 : }

11 : int str_len(char *p) //사용자 정의함수
12 : {
13 :        int i = 0;
14 :        while(p[i] != '\0'){  //문자열의 끝이 나올때까지 i 값을 증가시킨다.
15 :                        i++;
16 :        }
17 :        return i;
18 : }

 

< 결과화면 >

 

<2> "strlen"함수 사용하기

 

1 : #include <stdio.h>
2 : #include <string.h>
3 : void main(){
4 :  size_t length;
5 :  char buf[80];

6 :  while(1)
7 :  {
8 :   puts("\nEnter a line of text: a blank line terminates.");
9 :   gets(buf);
10 :  length = strlen(buf); // 간단히 사용해주면 끝! <string.h>에 정의되어있는 함수이다.

11 :  if(length !=0)
12 :  printf("\nThat line is %u characters long.", length);
13 :  else
14 :  break;
15 :  }
16 : }

 

< 결과화면 >


 

 

= strlen()에 전달되는 인수는 길이를 계산하기 원하는 문자열에 대한 포인터이다.

= 함수 strlen() 은 널 문자를 포함하지 않고 str에서부터 널 문자 사이에 있는 문자의 개수를 돌려준다.

 

'Backend > C' 카테고리의 다른 글

포인터(pointer)란 무엇인가?  (0) 2012.04.12
Call by value & call by reference  (0) 2012.04.12
argc, argv를 이용한 간단한 사칙연산.  (0) 2012.04.12
strcpy()함수  (0) 2012.04.12
파일을 여러 가지 모드로 열기  (0) 2012.04.12