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

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++;

 

 1 /* Copyright (C) 

 2  * 2012 - peng.wu

 3  * This program is free software; you can redistribute it and/or

 4  * modify it under the terms of the GNU General Public License

 5  * as published by the Free Software Foundation; either version 2

 6  * of the License, or (at your option) any later version.

 7  * 

 8  * This program is distributed in the hope that it will be useful,

 9  * but WITHOUT ANY WARRANTY; without even the implied warranty of

10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

11  * GNU General Public License for more details.

12  * 

13  * You should have received a copy of the GNU General Public License

14  * along with this program; if not, write to the Free Software

15  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

16  * 

17  */

18 

19 #include "stack.h"

20 

21 int count_word(char* string)

22 {

23     int i=0,count=0;

24 

25     if(string == NULL)

26     return 0;

27 

28     while(string[i])

29     {

30     if(string[i] == 0x20)

31     {

32         count++;

33     }

34     

35     i++;

36     }

37     count+=1;

38 

39     return count;

40 }

41 

42 char* word[30];

43 

44 char** split_string(char* string)

45 {

46     int i=0,count=0;

47     char* header;

48     char* buffer;

49     buffer=malloc(100);

50     memset(buffer,0x0,100);

51 

52     strcpy(buffer,string);

53     header = buffer;

54 

55     if(string == NULL)

56     return 0;

57 

58     while(buffer[i])

59     {

60     if(buffer[i] == 0x20)

61     {

62         buffer[i] = '\0';

63         word[count] = header;

64         printf("%s\n",word[count]);

65         header = header+i+1;

66         buffer = header;

67         count++;

68         i=0;

69         continue;

70     }

71     

72     if(buffer[i]=='\0')

73     {

74         word[count]=buffer;

75         printf("%s\n",word[count]);

76     }

77     i++;

78     }

79 

80     return ;

81 }

82 

83 int main(int argc,char* argv[])

84 {

85     char* string="To be or not to be, this is a question!";

86     int count=0;

87     int i;

88 

89     count=count_word(string);

90     printf("word count is :%d\n",count);

91     split_string(string);

92 

93     return 1;

94 

95 }

 

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

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

 

你可能感兴趣的:(字符串)