c) 문자열에 나온 알파벳 몇 번나왔는지 출력하기

조회수 442회
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

int main(void)

{

char *src = "aaabbb";

char* output="a";

char eng[26] = { 0 }; 

char string[10] = { 0 };

for (int i = 'a'; i <= 'z'; i++)

{

int count = 0;

    for (int j = 0; j < strlen(src); j++)
    {
        if (i == src[j])
        {
            count++;
            int index = (int)i-97;
            eng[index] = count; 
        } //알파벳나온만큼 저장
    }

}
printf("src=%s\n", src);
for (int i= 'a'; i <= 'z'; i++)
{
    if (eng[(int)i-97] > 0)
    {

        sprintf(string, "%c%d", (char)i, eng[(int)i-97]);
        strcpy(output, string);

    }

}
printf("%s", output);

return 0;
}

src에 aaabbb라는 문자열이 초기화돼 있잖아요. 이걸 output이라는 문자열 변수에 a3b3라고 저장하고 싶습니다. 그래서 마지막 for문에서 빈 문자열 output에 string을 붙여넣기를 하려고 하는데 저 부분에서 오류가 나네요. output이 문제인거 같은데 어떻게 바꿔야하나요?

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • output이 데이터를 변경할 수 있는 공간을 가리켜야 합니다. 위 코드는 변경할 수 없는 "a"라는 문자열을 가리키고 있네요.

    배열을 이용하거나 메모리 동적할당을 이용해야 합니다.

    아래 코드 참고하세요.

    • 코드
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char* src = "aaabbb123gghihiqqq";
        char output[20] = { 0, };
        char eng[26] = { 0, };
        char string[10] = { 0, };
    
        for (int i = 'a'; i <= 'z'; i++)
        {
            int count = 0;
    
            for (size_t j = 0; j < strlen(src); j++)
            {
                if (i == src[j])
                {
                    count++;
                    int index = (int)i - 97;
                    eng[index] = count;
                } //알파벳나온만큼 저장
            }
        }
        printf("src=%s\n\n", src);
        for (int i = 'a'; i <= 'z'; i++)
        {
            if (eng[(int)i - 97] > 0)
            {
                sprintf(string, "%c%d", (char)i, eng[(int)i - 97]);
                strcpy(output, string);
                printf("%s\n", output);
            }
        }
    
        return 0;
    }
    
    • 결과

    이미지

    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)