Programming Language/C2010. 10. 14. 19:32

 

Mystrcmp.c 

Mystrcmp공백제거.c (+ 공백제거 )


두 문자열의 크기를 비교해주는 함수를 구현해 봅니다.





/*
실습) 주어진 두 문자열의 크기 (사전상의 순서) 를 비교해주는 함수 mystrcmp(s,t)를 만드시오.

/maint에서
  -입력은 getchar() 사용할 것.
  -입력의 끝은 'n'
  -call은 result=mystrcmp(s,t);
  -출력은 printf("%d\n",result);
 
 /function에서
 -ps배열의 내용 > pt배열의 내용이면 return 1;
 -             ==                   return 0;
 -              <                   return -1;
  
   /이때,공백은 무시하고 비교하시오.
   -"ABC" ≡ " AB  C" ≡ "A   B C"
*/


#include<stdio.h>
#define MAX 30

int mystrcmp(char s[], char t[]);

int main(void){
 char s[MAX];
 char t[MAX];
 int cnt=0;
 char str;
 int result;
 puts("두 문자열의 사전상 순서로 크기를 비교해주는 프로그램.");
 puts("");
 puts("크기를 비교할 첫번째 문자열을 입력하시오. : ");
 
 while((s[cnt]= getchar()) != '\n'){
  cnt++;
 }
 s[cnt+1] = '\0';
 
 puts("크기를 비교할 두번째 문자열을 입력하시오. : ");
 
 cnt=0;
 while((t[cnt] = getchar()) != '\n'){
  cnt++;
 }
 t[cnt+1] = '\0';
 
 //비교
 
 
 result=mystrcmp(s,t);
 if(result==0)
  puts("0: 두 단어는 사전순서가 같습니다.");
 else if(result==1)
  printf("1: 두 단어중 %s가 더 앞장에 있습니다.\n",t);
 else if(result==-1)
  printf("-1: 두 단어중 %s가 더 앞장에 있습니다.\n",s);
 printf("%d",result);
 
 
 return 0;
}


int mystrcmp(char s[],char t[]){
 int i=0,j=0;
 int x=0;
 
 for(; ((strlen(s)>strlen(t)) ? (i<strlen(s)) : (i<strlen(t))) ; i++,j++){
  while(s[i]==' ')
   i++;
  while(t[j]==' ')
   j++;
  if(s[i]>t[j]){
   x=1;
   break;
  }
  if(s[i]<t[j]){
   x=-1;
   break;
   }
  if(s[i]==t[j])
   x=0;
 }
 
 
 
 return x;
}
 

이 글은 스프링노트에서 작성되었습니다.

Posted by BLUE-NOTE