본문 바로가기
Code/C

[C언어] 내장함수 비교 - strchr, strrchr / strstr, strnstr / strcmp, strncmp

by 코드포휴먼 2020. 10. 8.

<string.h>에 있는 문자열 관련 함수를 정리한다.

레퍼런스는 man 가이드다.

 

 

strchr와 strrchr 비교
RETURN 항목에서 말하는 'character'는 byte를 의미한다.

PROTOTYPE #include <string.h>
char *strchr(const char *s, int c);
#include <string.h>
char *strrchr(const char *s, int c);
NAME locate character in string
DESCRIPTION - The strchr() function locates the first occurrence of c (converted to a char) in the string pointed to by s.  
- The terminating null character is considered to be part of the string; therefore if c is `\0', the functions locate the terminating `\0'.
- The strrchr() function is identical to strchr(), except it locates the last occurrence of c.
RETURN

- a pointer to the first occurrence of the character c in the string s - a pointer to the last occurrence of the character c in the string s
- NULL if the character does not appear in the string.
- a pointer to the terminator
: The terminating null byte is considered part of the string, so that if c is specified as '\0', these functions return a pointer to the terminator.

 

 

strstr과 strnstr 비교

PROTOTYPE #include <string.h>
char *strstr
(const char *haystack, 
const char *needle);
#include <string.h>
char *strnstr
(const char *haystack,
const char *needle, size_t len);
NAME locate a substring in a string
DESCRIPTION - The strstr() function locates the first occurrence of the null-terminated string needle in the null-terminated string haystack. - The strnstr() function locates the first occurrence of the null-terminated string needle in the string haystack, where not more than len characters are searched.
- Characters that appear after a `\0' character are not searched.
RETURN

- a pointer to the first character of the first occurrence of needle
haystack
: if needle is an empty string
NULL
: if needle occurs nowhere in haystac

함수 프로토타입의 매개변수는 haystack과 needle인데 '건초더미에서 바늘찾기' 문구에서 따온 듯하다.

 

 

strcmp와 strncmp 비교

문자열을 비교하는 함수다.

s1이 s2보다 작거나, 일치하거나, s2보다 큰 경우, 0보다 작거나, 같거나, 0보다 큰 정수를 반환한다.

'\200' 문자는 ASCII Code 128(decimal)에 해당하는 문자다.

PROTOTYPE #include <string.h>
int strcmp(const char *s1,
const char *s2);
#include <string.h>
int strncmp(const char *s1, 
const char *s2, size_t n);

NAME compare two strings

DESCRIPTION
- The strcmp() and strncmp() functions lexicographically compare the null-terminated strings s1 and s2.
- Comparison is done in format of 'unsigned characters',  so `\200' is greater than `\0'.


- The strncmp() function compares not more than n characters.
- Characters that appear after a `\0' character are not compared, because strncmp() is designed for comparing strings rather than binary data.
RETURN

an integer less than, equal to, or greater than zero
(the difference between the first two differing bytes)

: if s1 is found, respectively, to be less than, to match, or be greater than s2.

 

 

댓글