소프트웨어/C

[2003년 기말 5번] 대소문자 변경 - 2

카켈 2007. 2. 5. 03:00



1. 목적

  - 문자/문자열에 대해 자유롭게 다룰줄 안다.
  - 내림차순의 알고리듬을 이해한다.
  - 문자열을 입력받을줄 안다.
 
2. 문제
  - 이전 문제에서 발전하여 2 문장을 입력받아 조작하여 출력한다.
  - 문자 속성 변경 함수는 ctype.h 에서 문자열 조작 함수는 string.h 에서 받아 쓴다.
  - 영어(알파벳)만 받아서 가공한다.
  - 대문자를 소문자로, 두 문장을 합치기, 알파벳 순으로 큰 값에서 낮은 값으로 3가지 출력을 한다.
  - 출력 예

두개의 문자열을 입력하세요.
첫번째 문자열 : Http://Signal.Korea.Ac.Kr/~ychlee
두번째 문자열 : Http://Cakel.Tistory.com
============================================
새로운 문자열 1 : HttpSignalKoreaAcKrychlee
새로운 문자열 2 : HttpCakelTistorycom
============================================
병합된 문자열 1 : HttpSignalKoreaAcKrychleeHttpCakelTistorycom
대문자로만 변환 : httpsignalkoreaackrychleehttpcakeltistorycom
정렬된 문자열   : yyttttttssrrrppooonmlllkkkiihhhgeeeeccccaaaa
============================================
Press any key to continue

3. 이해
  - 문자와 문자열의 차이를 알고 제대로 썼을까?
  - 이전 문제를 정확히 알고 있었는가?
  - 간단한 알고리듬을 구현할수 있나?

4. 해결코드

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main()
{
 char input_1[255], input_2[255], output_1[255], output_2[255];
 char concat[255], sort[255];
 int i = 0;
 int j = 0;
 int length = 0;
 char swap;

 printf("두개의 문자열을 입력하세요.\n");
 printf("첫번째 문자열 : "); gets(input_1);
 printf("두번째 문자열 : "); gets(input_2);
 printf("============================================\n");

 while(input_1[i])
 {
  if ( isalpha(input_1[i]) )
  {
   output_1[j] = input_1[i];
   j++;
  }
  i++;

 }
 output_1[j] = NULL;
 i = 0; j = 0;

 while(input_2[i])
 {
  if ( isalpha(input_2[i]) )
  {
   output_2[j] = input_2[i];
   j++;
  }
  i++;

 }
 output_2[j] = NULL;
 i = 0; j = 0;

 printf("새로운 문자열 1 : %s\n", output_1);
 printf("새로운 문자열 2 : %s\n", output_2);
 printf("============================================\n");

 strcpy(concat,output_1);
 strcat(concat,output_2);

 
 printf("병합된 문자열 1 : %s\n", concat);
 printf("대문자로만 변환 : ");

 while(concat[length])
 {
  sort[length] = tolower(concat[length]);
  putchar(sort[length]);
  length++;

 }
 
 sort[length] = NULL;
 putchar('\n');
 
 for(i = 0; i < length; i++)
 {
  for(j = i + 1; j < length ; j++)
   if(sort[i] < sort[j])
   {
    swap = sort[j];
    sort[j] = sort[i];
    sort[i] = swap;
   }

 }
 
 printf("정렬된 문자열   : %s\n",sort);
 printf("============================================\n");

 return 0;
}

5. 코드해설
  - 이전 문제에서 썼던 islower, toupper 함수를 그대로 활용합니다.
  - 우선 isalpha 함수를 써서 영어인지 받고 난뒤에 저장을 합니다.
  - 두 문장을 합치는 strcat 함수는 string.h 에 저장되어 있습니다.
  - 내림차순 정렬 알고리듬은 앞에 해당하는 문자가 뒤의 값보다 작을 경우(먼저 나오는 문자) swap
    알고리듬을 써서  바꾸는 방식입니다. 간단하게 구현가능해서 함수로 구현하지 않고 inline 으로
    구현했습니다.
  - scanf 로 문장을 받을수 있지만 띄워쓰기에서 문제가 발생하므로 gets 함수를 썼습니다.

6. 추가정보
  - http://www.cplusplus.com/reference/clibrary/cctype/ : ctype 제공 함수(toupper, isalpha, tolower 함수)
  - http://www.winapi.co.kr/clec/cpp1/12-1-2.htm : strcat 함수