C语言trim()实现

如题,代码如下:

#include 
#include 
#include 

//空白字符有: ' '(中间是空格), \t, \r, \n
char* trim(char *str) {
	int first = -1; //第一个空白字符的下标
	int last = -1; //最后一个空白字符的下标
	//找到第一个非空白字符
	for (int i = 0; str[i] != '\0'; i++) {
		if (str[i] != ' '
			&& str[i] != '\t'
			&& str[i] != '\n'
			&& str[i] != '\r') {
			first = i;
			break;
		}
	}
	if (first == -1) { //全是空白字符
		str[0] = '\0';
		return str;
	}

	//保存最后一个非空白字符的指针
	for (int i = first; str[i] != '\0'; i++) {
		if (str[i] != ' '
			&& str[i] != '\t'
			&& str[i] != '\n'
			&& str[i] != '\r') {
			last = i;
		}
	}

	//在最后一个非空白字符的后面赋值'\0'
	str[last + 1] = '\0';
	return str + first;
}
int main() {
	//测试数据
	char strs[][40] = {
		"",
		"      ",
		"   akklp  ",
		"  fsj dfk ",
		"     aaaa\t   \r\nbbbb  \t    \r  \n   "
	}; //注意\r是回到当前行的开头,利用\r能够覆写已经打印的字符
	for (int i = 0; i < 5; i++) {
		char *res = trim(strs[i]);
		printf("#%s#\n", res);
	}
	return 0;
}


实现效果如图:

C语言trim()实现_第1张图片

你可能感兴趣的:(C)