我试图在 C 中的一个句子中翻转每个单词,以便类似于:
“I like big dogs”会变成:“dogs big like I”
到目前为止,我有以下代码:
// 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)
}
任何帮助深表感谢。谢谢!