CS/๐Ÿ“–

strcmpํ•จ์ˆ˜

estherseo 2022. 4. 29. 18:12

๋‘ ๋ฌธ์ž์—ด์ด ๊ฐ™์€์ง€ ๋น„๊ตํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค.

 

strcmp ์›ํ˜•

int strcmp(const *_Str1, char const *_Str2);

 

strcmp ๋ฐ˜ํ™˜๊ฐ’

- ์•„์Šคํ‚ค์ฝ”๋“œ ๊ธฐ์ค€

str1 > str2 : 1๋ฐ˜ํ™˜
str1 < str2 : -1๋ฐ˜ํ™˜
str1 = str2 : 0๋ฐ˜ํ™˜

 

์˜ˆ์ œ์ฝ”๋“œ

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

int main() {
	char password[] = "aaaa";
	char user[] = "b";

	int result = strcmp(password, user);

	if ( result == 0) {
		printf("\nFlag is \"Welcome\"\n");
	}
	else if (result < 0) {
		printf("\nResult : %d\n", result);
	}
	else if (result > 0) {
		printf("\nResult : %d\n", result);
	}

	return 0;
}

str1 = aaaa, str2 = b

result = -1

 

str1 = aaba, str2 = aabaa

result = -1

 

์ถœ์ฒ˜ :&nbsp;https://dojang.io/mod/page/view.php?id=346

 

strcmp ๊ตฌํ˜„

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

int mystrcmp(char const* str1, char const* str2) {
	int i, is_equal=1;

	for (i = 0; 1; i++) {
		if (*(str1 + i) != *(str2 + i)) {
			is_equal = 0;
			break;
		}
		//flag๊ฐ€ NULL ๋ฌธ์ž(ASCII๊ฐ’ 0)์ธ ๊ฒฝ์šฐ ์ค‘๋‹จ
		if (*(str1 + i) == 0) break;
	}
	if (is_equal == 1) {
		return 0;
	}
	else {
		if (*(str1 + i) > * (str2 + i)) return 1;
		else return -1;
	}
}

int main() {
	char string1[] = "AAAA";
	char string2[] = "AAAA";

	int result = mystrcmp(string1, string2);

	if ( result == 0) {
		printf("๋‘ ๋ฌธ์ž์—ด์ด ๊ฐ™์Šต๋‹ˆ๋‹ค.\n");
	}
	else if (result < 0) {
		printf("str1\"%s\" < str2\"%s\"\n", string1, string2);
	}
	else if (result > 0) {
		printf("str1\"%s\" > str2\"%s\"\n", string1, string2);
	}

	return 1;
}

 

 

Reference:

๋”๋ณด๊ธฐ

 

 

 

 

์ž˜๋ชป๋œ ๋ถ€๋ถ„์ด ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค !! ๋ถ€์กฑํ•œ ์ ์€ ๋Œ“๊ธ€๋กœ ํ”ผ๋“œ๋ฐฑ ๋ฐ”๋ž๋‹ˆ๋‹ค :)