문자열의 사용

C : 2007. 11. 2. 16:36
* 문자열 - 널 종료 문자 배열

* 널(null) == 0(거짓)

*gets();     - 사용자가 enter를 입력할때까지 문자들을 읽는다.


@<string.h> 헤더파일을 사용하는 함수

*strcpy(to, from);  - from을 to에 복사  
*strcat(to, from);  - from을 to 뒤에 추가    
*strcmp(s1, s2);    - 비교, 같으면 0 반환  
                              s1<s2 - 0보다 작은 값.  
                              s1>s2 - 0보다 큰 값.

*strlen(str);       - 문자열의 길이/문자수를 반환.


p.178_1
#include <stdio.h>
#include <string.h>

int main(void)
{
 char str1[80], str2[80];
 int i;


 printf("Enter the first string: ");
 gets(str1);
 printf("Enter the second string: ");
 gets(str2);


//문자열의 길이 출력

 printf("%s is %d chars long\n", str1, strlen(str1));
 printf("%s is %d chars long\n", str2, strlen(str2));


//문자열 비교

 i= strcmp(str1, str2);
 if(!i) printf("The strings are equal.\n");
 else if(i<0) printf("%s is less then %s\n", str1, str2);
 else printf("%s is greater then %s\n", str1, str2);


//공간이 충분할때 str1끈에 str2를 연결

 if(strlen(str1)+ strlen(str2)<80) {
  strcat(str1, str2);
  printf("%s\n", str1);
 }


//str2를 str1에 복사

 strcpy(str1, str2);
 printf("%s %s\n", str1, str2);

 return 0;
}

p.179_2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
 char command[80], temp[80];
 int i, j;
 for( ; ;) {
  printf("Operation? \n add\n subtract\n divide\n multiply\n quit\n : ");
  gets(command);

  if(!strcmp(command, "quit")) break;
  printf("Enter first number: ");
  gets(temp);
  i = atoi(temp);                         //문자열 인수가 표현하는 수와 동일한 정수값을 반환

  printf("Enter second number: ");
  gets(temp);
  j = atoi(temp);

  if(!strcmp(command, "add")) printf("%d\n", i+j);
  else if(!strcmp(command, "subtract")) printf("%d\n", i-j);
  else if(!strcmp(command, "divide")) {
   if(j) printf("%d\n", i/j);
  }
  else if(!strcmp(command, "multiply")) printf("%d\n", i*j);
  else printf("Unknown command. \n");
 }

 return 0;
}

Posted by 청웨일