c - 如何以标准方式修剪前导/尾随空格?

标签 c string whitespace trim

是否有一种干净的、最好是标准的方法来从 C 中的字符串中删除前导和尾随空格?我会推出我自己的,但我认为这是一个具有同样常见解决方案的常见问题。

最佳答案

如果可以修改字符串:

// Note: This function returns a pointer to a substring of the original string.
// If the given string was allocated dynamically, the caller must not overwrite
// that pointer with the returned value, since the original pointer must be
// deallocated using the same allocator with which it was allocated.  The return
// value must NOT be deallocated using free() etc.
char *trimwhitespace(char *str)
{
  char *end;

  // Trim leading space
  while(isspace((unsigned char)*str)) str++;

  if(*str == 0)  // All spaces?
    return str;

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace((unsigned char)*end)) end--;

  // Write new null terminator character
  end[1] = '\0';

  return str;
}

如果你不能修改字符串,那么你可以使用基本相同的方法:

// Stores the trimmed input string into the given output buffer, which must be
// large enough to store the result.  If it is too small, the output is
// truncated.
size_t trimwhitespace(char *out, size_t len, const char *str)
{
  if(len == 0)
    return 0;

  const char *end;
  size_t out_size;

  // Trim leading space
  while(isspace((unsigned char)*str)) str++;

  if(*str == 0)  // All spaces?
  {
    *out = 0;
    return 1;
  }

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace((unsigned char)*end)) end--;
  end++;

  // Set output size to minimum of trimmed string length and buffer size minus 1
  out_size = (end - str) < len-1 ? (end - str) : len-1;

  // Copy trimmed string and add null terminator
  memcpy(out, str, out_size);
  out[out_size] = 0;

  return out_size;
}

关于c - 如何以标准方式修剪前导/尾随空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/122616/

相关文章:

c++ - C++ 中的 Random() 效率

c - 我的 C 代码中的逻辑错误

Rebol 或 Red 中的字符串搜索

xml:space ="preserve"对 XML 属性之间的空间有影响吗?

java - 获取两个以空格分隔的数据并在java中计算

c - 使用 C 在 .map 文件中搜索

c - 麻烦 : C Declaration of integer array of unknown size

php - 在 PHP 中的 <img> 标签的开头和结尾附加 <figure> 标签

java - 将此字符串转换为返回 Double

java - 使用Java解析时如何在文档元素之前保留空格?