How do I trim leading/trailing whitespace in a standard way?

http://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way

关于去除字符串的頭尾的空格键(思路可以扩展到其他的符号)。

分为两种情况,

1. 第一种为可以对此字符串改变的,如字符数组,堆中(calloc和malloc)分配的空间,还有一些buffer(TCP传过来的,不过也是通过以上方法来放的,只是感觉分一下,呵呵)。

char *trimwhitespace(char *str)
{
  char *end;

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

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

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

  // Write new null terminator
  *(end+1) = '\0';

  return str;
}


2. 第二种为无法对传入的字符做出改变的,那就需要你自己申请一片空间(数组,堆都可以)来放改变之后的字符串。

char *trimwhitespace(char *str)
{
  char *end;

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

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

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

  // Write new null terminator
  *(end+1) = '\0';

  return str;
}
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(*str)) str++;

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

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace(*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;
}

后记:经过测试,木有发现bug状况,逻辑比较简单, 先对传入的字符串进行判断,看看是不是空或者纯空格符,然后消除头和尾,再传出来。

            看老外的讨论,对第一个有疑义,就是假如你传入的是动态生成的,那么你需要自己在main函数(假设在main里面调用)自己free掉,不然内存泄漏了~~~当然数组无所谓了~~~

            恩,最好在注释里面说明下~~~


ps:大家看看有没有bug~~~




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值