消除字符串空格

来源:互联网 发布:淘宝房源 编辑:程序博客网 时间:2024/05/29 10:02

一、概述

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

去掉一个字符串的首尾空格,单词之间的空格,如果有多个则合并为一个,例如:“  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 youchar* 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 youchar* test = "  i love   china            and i  love you       ";printf("%s", FormatString(test));return 0;}
上面两个算法都没有直接对参数str进行操作,而是将其拷贝至新的内存区,然后进行操作。原因很简单,如果传递的参数是字符串常量,则直接对参数进行处理是不行的,会报错(字符串常量存储在静态存储区,不能进行写操作)。

0 0
原创粉丝点击