티스토리 뷰

문자열의 길이 및 탐색

문자열의 끝을 알 수 있는 방법은 무엇일까?

인덱스 문자가 널 종단 문자와 일치하는지를 비교할 수도 있겠지만

<string.h> 라이브러리의 strlen 함수를 이용하는 것이 좋다.

strlen은 문자열의 길이를 알려주는 함수이다.

 

 

문자열의 탐색 및 수정

소문자를 대문자로 바꾸는 방법은 무엇일까?

 

첫번째 방법은 ASCII 코드를 찾아서

소문자와 대문자의 차이가 32이므로 소문자 - 32를 해서 출력한다.

이미 대문자라면 그대로 출력한다.

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

int main(void)
{
    string s = get_string("Before: ");
    printf("After:  ");
    for (int i = 0, n = strlen(s); i < n; i++)
    {
        if (s[i] >= 'a' && s[i] <= 'z')
        {
            printf("%c", s[i] - 32);
        }
        else
        {
            printf("%c", s[i]);
        }
    }
    printf("\n");
}

 

 

두번째 방법은 <ctype.h> 라이브러리의 toupper 함수를 이용한다.

toupper 함수에 소문자를 넣으면 알아서 대문자로 변환해준다.

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

int main(void)
{
    string s = get_string("Before: ");
    printf("After:  ");
    for (int i = 0, n = strlen(s); i < n; i++)
    {
        printf("%c", toupper(s[i]));
    }
    printf("\n");
}

 

 

 

출처: www.boostcourse.org/cs112

'부스트코스 > 3. 배열' 카테고리의 다른 글

[CS50] 3.7 명령행 인자  (0) 2021.01.23
[CS50] 3.5 문자열과 배열(1)  (0) 2021.01.23
[CS50] 3.4 배열(2)  (0) 2021.01.23
[CS50] 3.3 배열(1)  (0) 2021.01.23
[CS50] 3.2 디버깅  (0) 2021.01.23
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함