NLP Learner in Switzerland

[C] Iteration and Recursion ::: 문자열에서 첫번째 대문자 찾아 인덱스를 반환하기 본문

Algorithm in C/Exercise

[C] Iteration and Recursion ::: 문자열에서 첫번째 대문자 찾아 인덱스를 반환하기

초코빵 2021. 4. 2. 10:00
728x90
반응형

 

 


까다로운 부분 알아가기

 


[1] 입력받을 string을 선언해주어야 한다.

▶ const를 사용해서 string의 최대 size를 제한해준다.

 

[2] 문자열내의 첫번째 대문자는 어떻게 찾아낼까?

▶ 문자는 ASCII 아스키코드로 숫자 치환되어 대소비교가 가능하다. 예를 들어서, 아스키코드로 'A'는 65이며, 'Z'는 90이다. 따라서 특정 문자가 'A'와 'Z'의 사이에 있으면 그 문자는 대문자라고 판단할 수 있다.

 

[3] iterative는 while loop 또는 for loop이 필요하겠군

▶ string의 특성상 맨 끝에 '\0'가 있으므로 \0를 만나기전까지 계속 읽어들인다. 대문자를 못찾고 끝나면, 즉 \0를 만나면 -1을 Return하라고 문제에 명시되어 있다.

 

[4] recursive는 if statement와 stop condition이 필요하겠군

▶ string의 특성상 맨 끝에 '\0'가 있으므로 \0를 만나면 stop시킨다(Return -1)는 내용을 if로 구현한다. 

 

[5] recurvise에서 stop condition을 만나려면 변화해야 하는 부분을 생각해본다.

▶ index를 계속 증가시켜서 '\0'까지 갈 수 있도록 하면 stop시킬 수 있다.

▶ 여기서 index는 pos라는 변수로 받으라고 되어있다.

 

#include <stdio.h>
const int MAX = 1001; ----------------------- [1]

int iterativeFirstUpper(char str[]){
    int i;
    while(str[i]!='\0'){ -------------------- [3]
        if(str[i]>='A'&&str[i]<='Z'){ ------- [2]
            return i;
        }
        i++;
    }
    return -1; ------------------------------ [3]
}

int recursiveFirstUpper(char str[], int pos){
    if(str[pos]=='\0'){ --------------------- [4]
        return -1;
    }
    if(str[pos]>='A'&&str[pos]<='Z'){ ------- [2]
        return pos;
    }
    return recursiveFirstUpper(str,pos+1); -- [5]
}

int main(){
    char str[MAX];
    printf("Input string: ");
    scanf("%[^\n]s",str);
    int pos;
    printf("Index of the first upper letter in iterative function: %d\n",iterativeFirstUpper(str));
    printf("Index of the First upper letter in recursive function: %d",recursiveFirstUpper(str,pos));
    return 0;
}

출력결과


 

Comments