字符串之单词原地逆转
生活随笔
收集整理的這篇文章主要介紹了
字符串之单词原地逆转
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/******************************************************************************
今天下午小奇問了我一個問題。字符串反轉easy,可是要是把字符串里的單詞反轉
比方:
輸入:I LOVE CAIHONG
輸出:I EVOL GNOHIAC 又該怎么弄呢思路:逐個單詞的反轉。
找到單詞的開始位置和結束位置的下標,把字符串和下標一傳遞給
Swap函數。這樣就反轉這個單詞了。
********************************************************************************/#include <iostream>void swap(char * s, int wordstarindex, int wordendindex) // 交換字符串s中 下標為[wordstarindex, wordendindex)的順序
{for (int k = wordstarindex; k < (wordstarindex + wordendindex) / 2; ++k){char tmp = s[k];//wordstarindex 和 wordendindex 的值不能變 s[k] = s[wordstarindex + wordendindex - k - 1];s[wordstarindex + wordendindex - k - 1] = tmp;}
}//char s[1000];int main()
{char str[1000];std::cout<<"please enter your strings.\n";std::cin.getline(str, sizeof str); for (int wordstarindex = 0, SpaceIndex = 0; str[SpaceIndex] != '\0'; ) // 當s[SpaceIndex]到達結尾時退出循環 {while (str[++SpaceIndex] != ' ' && str[SpaceIndex] != '\0') ; // 從左到右找到空格的下標SpaceIndexswap(str, wordstarindex, SpaceIndex); // 交換s[wordstarindex, SpaceIndex)的順序 wordstarindex = SpaceIndex + 1; // 將SpaceIndex的下一個下標賦值給wordstarindex }std::cout << str; // 輸出交換后的字符串 return 0;
}
轉載于:https://www.cnblogs.com/yutingliuyl/p/7205209.html
總結
以上是生活随笔為你收集整理的字符串之单词原地逆转的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在ubuntu上搭建hustoj?
- 下一篇: CSS深入理解学习笔记之z-index