Skip to content

c언어 문자열 문제 도와주세요 #704

@nakyung55

Description

@nakyung55

공백을 포함하는 문자열 str1과 공백을 포함하지 않는 문자열 str2를 입력 받아, str2가 str1에 몇 번 나타나는지, 그 횟수를 출력하는 프로그램을 작성하시오. 입력 받는 문자열의 크기는 최대 100 이다. (단, AAA에는 AA가 1개 있는 것으로 한다. 즉 이미 횟수 계산에 사용된 문자는 다음 계산에 포함하지 않는다.)

#include <stdio.h>
#include <string.h>
#pragma warning(disable:4996)

int main() {
char str1[101], str2[101];
int cnt = 0, len1, len2;

scanf("%[^\n]s", str1);
scanf("%s", str2);
len1 = strlen(str1);  
len2 = strlen(str2); 

for (int i = 0;i < len1;i++) {
    int flag = 1;
    for (int j = 0;j < len2;j++) {
        if (str1[i + j] != str2[j]) flag = 0;
    }
    if (flag == 1) { 
        cnt++;
        i = i + len2 - 1;
    }
}

printf("%d", cnt);
return 0;

}

str1=rrr,str2=rr일 때

i=0일 때
j=0일 때 str1[0]=str2[0], j=1일 때 str1[1]=str2[1]이므로 cnt=1
i=i+2-1=1로 이동

i=1일 때
j=0일 때 str1[1]=str2[0], j=1일 때str[2]=str2[1]이므로 cnt=2

라서 2가 출력될 줄 알았는데 왜 1이 출력되는지 모르겠어요

Metadata

Metadata

Assignees

No one assigned

    Labels

    question질문으로 사용될 이슈

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions