2013-02-14 57 views
-1

我想翻轉每個單詞在C句話讓類似:在C語句中翻轉單個單詞?

「我喜歡大狗」將成爲「狗大似我」

我有下面的代碼至今:

// the following effectively flips a sentence so "I like big dogs" would become 
    "sgod gib ekil I" 

for (i=0;i<length/2;i++){ // length is length of the string 
    temp=ret[length-(i+1)]; //ret is the string 
    ret[length-(i+1)]=ret[i]; 
    ret[i]=temp; 
} 
    //now this part should flip each individual word to the right way 
//pos and lengthPlacer are both initialized as 0 
while(pos<length){ 
    lengthPlacer++; 
    if (ret[lengthPlacer]==' ' || lengthPlacer==length){ 
for (i=pos;i<(lengthPlacer)/2;i++){ 
    temp=ret[lengthPlacer-(i+pos+1)]; 
    ret[lengthPlacer-(i+pos+1)]=ret[i]; 
    ret[i]=temp; 
} 
    pos=lengthPlacer+1; 
    } 
} 
return ret; //this returns "dogs gib ekil I" unfortunately (only flips 1st word) 

} 

任何幫助,非常感謝。謝謝!

+0

可以分割字符串,存儲陣列,然後從高指數 – 2013-02-14 02:02:33

+1

打印這個值應該在這裏展示你的代碼,並問一個具體問題有關的具體問題。從算法上講,你可以反轉每個單詞,然後顛倒整個字符串。 – 2013-02-14 02:02:54

+0

對不起。我現在修復了我的代碼以顯示我的問題。 – user2019594 2013-02-14 02:04:24

回答

0

您正在將pos變量與lengthPlacer變量同時遞增。你需要一個內部循環先遞增,直到空間,然後是反向循環。

while(pos<length){ 
    while (lengthPlacer < length) 
    if (ret[lengthPlacer]==' ') break; 
    } 
    next = pos + (lengthPlacer-pos)/2; 
    while (pos < next){ 
    etc... 
    } 
    // Also here skip any spaces that might be dangling 
}