프로그래밍/프로그래머스
C++ 가운데 글자 가져오기(프로그래머스)
devsu
2020. 5. 31. 17:13
프로그래머스_가운데 글자 가져오기
문자열 처리

문제 해석
이 문제를 풀기위해 이해해야 할 내용은 다음과 같습니다.
목표
문자열 가운데 글자 구하기
방법
1. 홀수인 경우 가운데 글자하나만 가져온다
2. 짝수인 경우 가운데 글자 두개를 가져온다
결과
문자열 가운데 글자 출력
통과한 코드
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#define _CRT_SECURE_NO_WARNINGS
char* solution(const char* s) {
int nLen = strlen(s);
int nIndex = nLen / 2;
char* answer;
if (nLen % 2)
{
answer = (char*)malloc(2);
memset(answer, 0, 2);
strncpy(answer, s + nIndex, 1);
}
else
{
answer = (char*)malloc(3);
memset(answer, 0, 3);
strncpy(answer, s + nIndex-1, 2);
}
return answer;
}
홀수 짝수를 확인하여 원하는 위치에 접근하여 글자를 가져와 출력하였다.