[C/C++] while문을 이용한 strchr, strrchr 사용법

pikamon·2023년 8월 14일
0

C/C++

목록 보기
7/9

1. strchr, strrchr

어떤 문자열에서 원하는 문자열을 찾을 때

strchr는 앞에서부터, strrchr는 뒤에서부터 찾는 함수이다.

2. 예제 코드

"Hello, world" 라는 문자열에서 'o'를 반복적으로 찾아나가고자 할 때,

2-1. strchr

strchr은 찾은 위치 + 1을 입력으로 다시 주면 된다.

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

int main(void)
{
	char str[] = "Hello, world!";
	char target = 'o';
	char *found;

	found = strchr(str, target);
	while (found)
	{
		size_t pos = found - str;
		printf("Found '%c' at position %ld\n", target, pos);
		found = strchr(found + 1, target);
	}
	return 0;
}

실행 결과

Found 'o' at position 4
Found 'o' at position 8

2-2. strrchr

strrchr은 찾은 위치의 값을 널문자로 초기화한 후 다시 돌리면 된다.

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

int main(void)
{
	char str[] = "Hello, world!";
	char target = 'o';
	char *found;
	
	while (found = strrchr(str, target))
	{
		size_t pos = found - str;
		printf("Found '%c' at position %ld\n", target, pos);
		str[pos] = '\0';
	}
	return 0;
}

실행 결과

Found 'o' at position 8
Found 'o' at position 4
profile
개발자입니당 *^^* 깃허브 https://github.com/pikamonvvs

1개의 댓글

comment-user-thumbnail
2023년 8월 14일

큰 도움이 되었습니다, 감사합니다.

답글 달기