去掉一个字符串的首尾空格,若中间有空格仅保留一个

#include<stdio.h>
char* replace(char *str,int more)
{
	char *ptr = str;
		while (*str!=' ')
		{
			char *m;
			if (*str == '\0')
			{
				m = str - more-1;
				*m = *str;
				break;
			}
			else
			{
				m = str - more;
				*m = *str;
				str++;	
			}
					 
		}
		 
		if (*str!='/0')
		
		{
				char *tem = str - more;
				*tem = *str;
				str;
		}
				return str;	
}
char* formatString(char *sourceString) {
	char *str = sourceString;
	 
	while (*str== ' ')
	{
		str++;
		
	}
	sourceString = str;
	int more = 0;
	while (*str != '\0')
	{
		
		if (*str == ' ')
		{
			str++;
			while (*str == ' ')
			{
				more++;
				str++;
				if (*str != ' ')
					break;
			}
			 str= replace(str, more);		 
		}
		else
			str++;
	}
	return sourceString;
}
int main()
{
	char str[] ="  I   love you   ";
	printf("%s\n",str);
	char* temp = formatString(str);
	printf("%s",temp);
	return 0;	 
}

猜你喜欢

转载自blog.csdn.net/u013250424/article/details/48264285
今日推荐