您的位置:首页 > 其它

以单词为单位翻转一个字符串

2012-08-19 21:33 295 查看
1. 以单词为单位翻转一个字符串;
input: To be or not to be, this is a question
ouput: question a is this, be to not or be To

解题思路:
* 如何界定一个单词; 是用空格来界定;
* 采用堆栈的数据结构,将单词一个个压入后再弹出即可;
* 堆栈的结点定义要求数据为字串;
* 其中关关键之处在于如何将字串分解为单词,存入在数组中

在内存中字串的存放形式如下:
To\20be\20or\20not\20to\20be,\20this\20is\20a\20question\0
要求分解后为:char* word[]={"To","be","or","not","to","be","this","is","a","question"}
这样处理之后,反转的方式就可以有多样的选择了;

首先可以看到分解单词的界定符为\20,如保要判断到一个\20字符之后将单词存入数组?
用伪程序表示如下:
pString = "To be or not to be,this is a question!"
header = pString
if(pString[i] == \20)
  pString[i] = \0
  word[count] = header
  header += i;
  count++;

/* Copyright (C)
* 2012 - peng.wu
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*
*/

#include "stack.h"

int count_word(char* string)
{
int i=0,count=0;

if(string == NULL)
return 0;

while(string[i])
{
if(string[i] == 0x20)
{
count++;
}

i++;
}
count+=1;

return count;
}

char* word[30];

char** split_string(char* string)
{
int i=0,count=0;
char* header;
char* buffer;
buffer=malloc(100);
memset(buffer,0x0,100);

strcpy(buffer,string);
header = buffer;

if(string == NULL)
return 0;

while(buffer[i])
{
if(buffer[i] == 0x20)
{
buffer[i] = '\0';
word[count] = header;
printf("%s\n",word[count]);
header = header+i+1;
buffer = header;
count++;
i=0;
continue;
}

if(buffer[i]=='\0')
{
word[count]=buffer;
printf("%s\n",word[count]);
}
i++;
}

return ;
}

int main(int argc,char* argv[])
{
char* string="To be or not to be, this is a question!";
int count=0;
int i;

count=count_word(string);
printf("word count is :%d\n",count);
split_string(string);

return 1;

}


运行结果如下,可以看出,最后一个单词的处理还不OK,不过留到明天处理:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐