6,
按單詞反轉字串
並不是簡單的字串反轉,而是按給定字串裡的單詞將字串倒轉過來,就是說字串裡面的單詞還是保持原來的順序,這裡的每個單詞用空格分開。例如:
here is www.fishksy.com.cn
經過反轉後變為:
www.fishksy.com.cn is here
如果只是簡單的將所有字串翻轉的話,可以遍歷字串,將第乙個字元和最後乙個交換,第二個和倒數第二個交換,依次迴圈。其實按照單詞反轉的話可以在第一遍遍歷的基礎上,再遍歷一遍字串,對每乙個單詞再反轉一次。這樣每個單詞又恢復了原來的順序。
*************************=
#include
using namespace std;
char* reverse_word(const char* str)
{int len = strlen(str);
char* restr = new char[len+1];
strcpy(restr,str);
int i,j;
for(i=0,j=len-1;i
int main()
{char* str = "here is the www.google.cn!";
cout<
如果考慮空間和時間的優化的話,當然可以將上面**裡兩個字串交換部分改為異或實現。
例如將char temp=restr[i];
restr[i]=restr[j];
restr[j]=temp;
改為restr[i]^=restr[j];
restr[j]^=restr[i];
restr[i]^=restr[j];
按單詞反轉字串
並不是簡單的字串反轉,而是按給定字串裡的單詞將字串倒轉過來,就是說字串裡面的單詞還是保持原來的順序,這裡的每個單詞用空格分開。例如 here is www.msjl.net 經過反轉後變為 www.msjl.net is here 如果只是簡單的將所有字串翻轉的話,可以遍歷字串,將第乙個字元和最後乙...
字串反轉,單詞反轉
一 字串反轉,共蒐集了 7 種方法 public class stringreversed public static void reverse1 string s char c s.tochararray 方法二 for int i 0 i s.length 2 i for char l c sy...
Python學習 字串按單詞反轉
第一天學python,做乙個作業 題目 字串按單詞反轉 必須保留所有空格 i love china 轉化為 china love i import string s i love china s1 list s.split 構建乙個空陣列 x 反向遍歷陣列 for c in reversed s1 ...