Algorithm 5 - Remove First and Last Character

Beast from the east·2021년 10월 6일
0

Algorithm

목록 보기
5/27

Q.

Description:
It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.

A)

char* remove_char(char* dst, const char* src)
{
  char *ptr = dst;
  while (*src)
  {
    if (*(src + 2) == '\0')
      break;
    *ptr = *(src + 1);
    ptr++;
    src++;
  }
  *ptr = '\0';
  return dst;
}

another solution
char *remove_char(char* dst, const char* src) {
    src ++;
    strncpy(dst, src, strlen(src)-1);
    dst[strlen(src)-1] = '\0';
    return dst;
} -> 'strnpy' does not guarantee the null character.
profile
Hello, Rabbit

0개의 댓글