2021. 3. 2. 19:36 c언어
C언어 - 단어 순서 정하기
#include<stdio.h>
#include<string.h>
int mystrcmp1(char[], char[]); // 단어 비교하기(공백 무시x)
int mystrcmp2(char[], char[]); // 단어 비교하기(공백 무시)
int main()
{
char s[20];
char t[20];
int i = 0, j = 0;
int result = 0;
printf("s배열 : ");
while ((s[i++] = getchar()) != '\n'); // s배열의 단어 입력
s[--i] = '\0';
printf("t배열 : ");
while ((t[j++] = getchar()) != '\n'); // t배열의 단어 입력
t[--j] = '\0';
result = mystrcmp2(s, t);
printf("%d\n", result);
return 0;
}
int mystrcmp1(char s[], char t[]) {
int i = 0;
while ((s[i] != '\0') || (t[i] != '\0')) { // 두 단어중 '\0' 값이 나올 때 까지
if (s[i] == t[i]) // 두 글자가 같으면 다음글자 비교
i++;
if (s[i] - t[i] < 0 ) //두 글자가 다를 때 s단어가 빠를경우 -1값 리턴
return -1;
else // t 글자가 빠를경우 1값 리턴
return 1;
}
if (s[i] == t[i])
return 0;
if (s[i] - t[i] < 0)
return -1;
else
return 1;
}
int mystrcmp2(char s[], char t[]) {
for (int i = 0, j = 0; (i < 20) && (j < 20); ++i, ++j) // s, t 배열 전체 검색을 위한 반복문
{
while (s[i] == ' ') // s 배열의 단어 공백 무시
{
if (++i >= 20) // 배열 크기를 넘어가면 멈춘다.
{
break;
}
}
while (t[j] == ' ') // t 배열의 단어 공백 무시
{
if (++j >= 20) // 배열 크기를 넘어가면 멈춘다.
{
break;
}
}
if (i >= 20) // s 배열이 먼저 검사할경우
{
if (j < 20) // 먼더 끝났으니 s배열이 더 앞에 나온다.
return -1;
else // 둘 다 같은 단어다.
return 0;
}
else if (j >= 20) // t 배열이 더 빠른 단어
{
return 1;
}
if ((s[i] == '\0') && (t[j] == '\0')) // 둘다 똑같은 단어
{
return 0;
}
if (s[i] < t[j]) // s가 빠른 단어
{
return -1;
}
else if (s[i] > t[j]) // j가 빠른 단어
{
return 1;
}
}
return 0;
}
'c언어' 카테고리의 다른 글
C언어 - 특정 글자 지우고 단어 반대로 출력하기 (0) | 2021.03.04 |
---|---|
수업에서 느낀점(변수) (0) | 2021.03.03 |
C언어 - Right shift (0) | 2021.03.02 |
C언어 - Left shift (0) | 2021.03.02 |
수업에서 느낀점 (0) | 2021.03.01 |