输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。例如输入“Iam a student.”,则输出“student. a am I”。
解一:
- /*Title: 10.翻转句子中单词的顺序:解一
- Author: gocode
- Date: 2012-10-16*/
- #include<iostream>
- using namespace std;
- void Reverse(char* start,char* end)//翻转字符串
- {
- if(start == NULL || end == NULL)
- return;
- char temp;
- while(start<end)
- {
- temp = *start;
- *start = *end;
- *end = temp;
- start++;
- end--;
- }
- }
- char* ReverceSentence(char* pstr)
- {
- if(pstr == NULL)
- return NULL;
- //先将整个句子翻转
- char* start=pstr;
- char* end= pstr + strlen(pstr) - 1;
- Reverse(start, end);
- start = pstr;
- end = pstr;
- //取出一个个单词,翻转之
- while(*start != '\0')
- {
- if(*start == ' ')//单词起始至非空格字符
- {
- start++;
- end++;
- continue;
- }
- else if(*end ==' ' || *end == '\0')//结束至空格或结束符前一个字符
- {
- Reverse(start,--end);
- start = ++end;
- }
- else
- end++;
- }
- return pstr;
- }
- int main()
- {
- char sentence[] = "I am a student!";
- cout<<sentence<<endl;
- char*reverced = ReverceSentence(sentence);
- cout<<reverced<<endl;
- system("pause");
- return 0;
- }
- /*Title: 10.翻转句子中单词的顺序:解二
- Author: gocode
- Date: 2012-10-16*/
- #include "tchar.h"
- #include <assert.h>
- #include <iostream>
- using namespace std;
- #define KEY_CHAR ' '
- // 反转起始位置为i32FirIndex,结束位置为i32EndIndex的字符串
- void ReverseString(char *pszStr, int i32FirIndex, int i32EndIndex)
- {
- assert(NULL != pszStr || i32FirIndex >= 0 || i32EndIndex >= 0);
- if (i32EndIndex <= i32FirIndex) return;
- char chTemp;
- int i32FirIdx = i32FirIndex;
- int i32EndIdx = i32EndIndex;
- for (; i32FirIdx < i32EndIdx; i32FirIdx++, i32EndIdx--)
- {
- chTemp = pszStr[i32FirIdx];
- pszStr[i32FirIdx] = pszStr[i32EndIdx];
- pszStr[i32EndIdx] = chTemp;
- }
- }
- bool IsNeedReverseString(char *pszStr, int nLen)
- {
- assert(NULL != pszStr || nLen > 0);
- bool bRet = false;
- for (int i32I = 0; i32I < nLen; i32I++)
- {
- if (KEY_CHAR == pszStr[i32I])
- {
- bRet = true;
- break;
- }
- }
- return bRet;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- char aszStr[] = {"I am a boy."};
- if (IsNeedReverseString(aszStr, strlen(aszStr)))
- {
- //Step 1:
- ReverseString(aszStr, 0, strlen(aszStr) - 1);
- //Step 2:
- int i32CurIdx = 0;
- for (int i32I = 0; i32I < (int)strlen(aszStr); i32I++)
- {
- if (KEY_CHAR == aszStr[i32I])
- {
- ReverseString(aszStr, i32CurIdx, i32I - 1);
- i32CurIdx = i32I + 1;
- }
- }
- ReverseString(aszStr, i32CurIdx, (int)strlen(aszStr) - 1);
- }
- cout << aszStr << endl;
- return 0;
- }