C语言除去字符串开头和末尾空格之trim()函数的实现

Trim()函数功能除去字符串开头和末尾的空格或其他字符,函数执行成功时返回删除了字符串首部和尾部空格的字符串。

char *trim(char *str)

C语言标准库中并没有trim()函数,比较遗憾,那么我们就来实现一个,哈哈。

一、 具体实现代码

#include <string.h>
#include <stdio.h>
#include <ctype.h>

// delete the front whitespace
char *left_trim(char *str)
{
	char *beginp = str;
	char *tmp = str;
	while(isspace(*beginp)) beginp++;
	while((*tmp++ = *beginp++));

	return str;
}

// delete the back whitespace
char *right_trim(char *str)
{
	char *endp;
	size_t len = strlen(str);

	if(len == 0) return str;

	endp = str + strlen(str) - 1;
	while(isspace(*endp)) endp--;
	*(endp + 1) = '\0';

	return str;
}

char *trim(char *str)
{
	str = left_trim(str);
	str = right_trim(str);

	return str;
}

int main(void)
{
	char *src[] =
	{
		"   hello world   ",
		"    hello world",
		"hello world   ",
		"hello world",
		"",
		NULL
	};
	char result[1024];
	
	for(int index = 0; src[index] != NULL; index++)
	{
		strcpy(result, src[index]);
		printf("[%s] -> [%s]\n", src[index], trim(result));          
	}

	return 0;
}

二、 运行结果

[ycxie@fedora Workspace]$ gcc string_trim.c -o string_trim -Wall
[ycxie@fedora Workspace]$ ./string_trim
[   hello world   ] -> [hello world]
[    hello world] -> [hello world]
[hello world   ] -> [hello world]
[hello world] -> [hello world]
[] -> []

Leave a Reply

Your email address will not be published. Required fields are marked *