最好的算法脱光用C开头和结尾的空格 [英] Best algorithm to strip leading and trailing spaces in C

查看:194
本文介绍了最好的算法脱光用C开头和结尾的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是用C剥离开头和结尾的空格最好的办法?

What is the best approach in stripping leading and trailing spaces in C?

推荐答案

您可以完全到位做到这一点。

You can do this entirely in place.

 void stripLeadingAndTrailingSpaces(char* string){

     assert(string);

     /* First remove leading spaces */

     const char* firstNonSpace = string;

     while(*firstNonSpace != '\0' && isspace(*firstNonSpace))
     {
          ++firstNonSpace;
     }

     size_t len = strlen(firstNonSpace)+1;         

     memmove(string, firstNonSpace, len);

     /* Now remove trailing spaces */

     char* endOfString = string + len;

     while(string < endOfString  && isspace(*endOfString))
     {
          --endOfString ;
     }

     *endOfString = '\0';

}

这篇关于最好的算法脱光用C开头和结尾的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆