如何在C语言中的字符串中删除所有空格和制表符? [英] How to remove all spaces and tabs from a given string in C language?
问题描述
什么C函数,如果有的话,从字符串中删除所有preceding空格和制表符?
What C function, if any, removes all preceding spaces and tabs from a string?
感谢。
推荐答案
在C语言中的字符串由一个指针标识,如的char * str中
,或可能是一个数组。无论哪种方式,我们可以宣布我们自己的指针将指向字符串的开头:
In C a string is identified by a pointer, such as char *str
, or possibly an array. Either way, we can declare our own pointer that will point to the start of the string:
char *c = str;
然后,我们可以让我们的指针以往任何空间般的人物移动:
Then we can make our pointer move past any space-like characters:
while (isspace(*c))
++c;
这将导致任何空格或制表符后移动,直到它并不指向一个空间,即指针向前。这使得原来不改变的字符串 - 我们刚刚改变了位置我们的指针 C
指向在
That will move the pointer forwards until it is not pointing to a space, i.e. after any leading spaces or tabs. This leaves the original string unmodified - we've just changed the location our pointer c
is pointing at.
您将需要此包括获得 isspace为
:
#include <ctype.h>
或者,如果你很高兴地定义自己的什么是空白字符想法,你可以只写一个前pression:
Or if you are happy to define your own idea of what is a whitespace character, you can just write an expression:
while ((*c == ' ') || (*c == '\t'))
++c;
这篇关于如何在C语言中的字符串中删除所有空格和制表符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!