您的位置:首页 > 其它

消除字符串空格

2015-09-07 17:11 375 查看

一、概述

这是自己面试时碰到的一个题目,题目大意如下:

去掉一个字符串的首尾空格,单词之间的空格,如果有多个则合并为一个,例如:“ i love china and i love you ”,则输出结果为:"i love china and i love you"。

先说一下自己的思路:

1、字符串首尾的空格比较容易,直接扫描一个去掉一个。

2、字符串中间的空格,需要分割出单词。然后这里有两种方法,一是将分割出的单词自己加上空格然后连接起来即可,一种是边分割边删除多余空格。下面的代码采用的是第二种方式。

贴上源码:

#include "stdafx.h"
#include <string.h>
#include <stdlib.h>

char* formatString(char *sourceString) {
int In = 1;   //标志是否进入了一个单词
int count = 0;//空格数
int index = 0;//下标

char*p = (char*)malloc(strlen(sourceString) + 1);
memcpy(p, sourceString, strlen(sourceString) + 1);

//先去除首尾的空格
while (*p == ' ')//去掉首部空格
    {
        p++;
    }

for (int i = strlen(p)-1; i >= 0; i--)//去掉尾部空格,将空格填充'\0'即可
    {
       if (p[i] == ' ')
          p[i] = '\0';
       else
          break;
    }

    //去除字符间的空格
char* temp = p;
while (*temp != '\0')
    { 
         index++;
 if (*temp == ' ')//到达单词外
 {
In = 0;
  }
else
 {
In = 1;//进入单词,必须去掉两个单词之间的空格
 //若有则去掉空格
if (count>1)
 {
for (int i = index-1; i <= strlen(p); i++)
 {
p[i - count+1] = p[i];
}
  index = index - count;
temp = temp - count;
 count = 0;
}
  if (count==1)//只有一个空格就不去掉
 {
count = 0;
 }    
 }
 if (In == 0)
 {
 if (*temp == ' ')//空格计数
 {
 count++;
}
}
temp++;
    }
return p;
}
int _tmain(int argc, _TCHAR* argv[])
{
    //i love china and i love you
char* test = "  i love   china            and i  love you   ";
char  test2[100] = "  i love   china            and i  love you   ";
printf("%s\n", formatString(test));
printf("%s\n", formatString(test2));
 return 0;
}


下面是运行结果图:



附:

下面的算法更加简洁,思路如下:

采用双下标循环,如果遇到单词则将其移动到新字符串(向前移动),遇到空格则保留第一个,剩余的忽略掉。代码如下,注释应该够清晰了吧:

#include "stdafx.h"
#include <string.h>
#include <stdlib.h>

char*  FormatString(char *str)
{
	int In = 0; //进入单词为1,出单词区进入空格区为0
        int i, j;//双下标
	char* pStr = (char*)malloc(strlen(str) + 1);
	memcpy(pStr, str, strlen(str) + 1);
	//双下标循环,i代表旧字符串,j代表新字符串
	for (i = 0, j = 0; *(pStr + i) != '\0'; i++)
	{
		if (*(pStr + i) != ' ')//进入单词</span>
		{
			In = 1;//设置标记
			*(pStr + j) = *(pStr + i);//拷贝单词到新字符串,这里不需要开辟新空间,直接向前移动即可。
			j++;
		}
		else
		{
			if (In == 1)//出单词遇到第一个空格,保留之
			{
				*(pStr + j) = ' ';
				j++;
			}
			In = 0; //出单词区,其余空格都忽略
		}
	}
        //处理字符串末尾空格
	if (*(pStr + j - 1) = ' ')  //末尾有空格则填充'\0'
		*(pStr + j - 1) = '\0';
	else  //末尾无空格
		*(pStr + j) = '\0';
	return pStr;
}

int _tmain(int argc, _TCHAR* argv[])
{
	//i love china and i love you
	char* test = "  i love   china            and i  love you       ";
	printf("%s", FormatString(test));
	return 0;
}
上面两个算法都没有直接对参数str进行操作,而是将其拷贝至新的内存区,然后进行操作。原因很简单,如果传递的参数是字符串常量,则直接对参数进行处理是不行的,会报错(字符串常量存储在静态存储区,不能进行写操作)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: