C
C 언어, 문자열 슬라이싱(일부분) 복사하기
수알치
2020. 9. 28. 14:30
C 언어, 문자열 슬라이싱(일부분) 복사하기
글. 오상문 sualchi@daum.net
다음 예제는 문자열에서 특정 부분만 가져와서 복사합니다.
#include <stdio.h>
#include <string.h>
// buf: 저장소, s: 문자열, start: 시작 인덱스, size: 잘라올 길이
char * strcpy_slice(char *buf, char *s, int start, int size)
{
if (strlen(s) > start) {
s += start; // 시작 위치로 변경
while (size-- > 0 && *s != '\0') // size가 0보다 크고, 문자열 끝이 지나지 않은 경우
*(buf++) = *(s++); // 복사
*buf = '\0'; // 끝에 널 문자 처리
}
return buf;
}
int main()
{
char s1[100];
char s2[] = "0123456789";
strcpy_slice(s1, s2, 5, 3); // 인덱스 5번부터 3글자 복사
printf("%s\n", s1); // 567
return 0;
}
<이상>
반응형