How do I safely remove spaces before and after?

Asked 1 years ago, Updated 1 years ago, 108 views

Everything I come up with is a cliche Is there a standard for removing space characters before/after?

I hope it's a very standard "look good, safe" code.

string c whitespace trimming

2022-09-22 22:18

1 Answers

/*
This function returns a pointer that points to a partial string of a string entered by the factor.
If the str that came in as a factor is dynamically allocated, there may be a memory leak, so please process it separately!
*/
char *trimwhitespace(char *str)
{
  char *end;

  // Remove the preceding space
  while(isspace(*str)) str++;

  If (*str == 0) // The string is blank
    return str;

  // Remove a space character
  end = str + strlen(str) - 1;
  while(end > str && isspace(*end)) end--;

  // New null at the end
  *(end+1) = 0;

  return str;
}
/*
Please set the output buffer large enough because the result is saved in the output buffer.
If the size is too small, the result will be cut
*/
size_t trimwhitespace(char *out, size_t len, const char *str)
{
  if(len == 0)
    return 0;

  const char *end;
  size_t out_size;

  // Remove the preceding space
  while(isspace(*str)) str++;

  If (*str == 0) // The string is blank
  {
    *out = 0;
    return 1;
  }

  // Remove a space character
  end = str + strlen(str) - 1;
  while(end > str && isspace(*end)) end--;
  end++;

  // Determines the size of the output size
  out_size = (end - str) < len-1 ? (end - str) : len-1;

  // Copy results and add a new null at the end
  memcpy(out, str, out_size);
  out[out_size] = 0;

  return out_size;
}


2022-09-22 22:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.