去除字符串中的空白符

2023-10-20 16:17:40 浏览数 (1)

函数提供三个功能,一种是去除左侧空格和TAB、另外一种是去除右侧的空格和TAB,最后一种则是去除所有空格和TAB,适当修改代码也可以去除ASCII中的9~13的其他空白符。具体实现如下:

代码语言:javascript复制
#include <stdio.h>
int StringStripWS(char* pStr, int type)
{
char* pStrback = pStr;
switch (type)
{
case 1: // 去除左侧空白字符
if (*pStrback == ‘ ‘  *pStrback == ‘t’)
{
while (*pStrback == ‘ ‘  *pStrback == ‘t’) pStrback  ;
while (*pStr   = *pStrback  );
}
break;
case 2: // 去除右侧空白字符
while (*pStr) pStr  ;
pStr–;
while (*pStr == ‘ ‘  *pStr == ‘t’)
{
*pStr = ‘’;
pStr–;
}
break;
case 3: // 去除所有空白字符
while (*pStr)
{
if (*pStr == ‘ ‘  *pStr == ‘t’)
{
pStr  ;
continue;
}
else
{
*pStrback   = *pStr  ;
}
}
*pStrback = ‘’;
break;
}
return 0;
}
int main(int argc, char* argv[])
{
char buf[] = “      my     name     is     dengjia      “;
printf(“原始字符串内容为 : –%s–n”, buf);
StringStripWS(buf, 1);
printf(“去除左侧空白符后 : –%s–n”, buf);
StringStripWS(buf, 2);
printf(“去除右侧空白符后 : –%s–n”, buf);
StringStripWS(buf, 3);
printf(“去除全部空白符后 : –%s–n”, buf);
return 0;
}

0 人点赞