-1

我试图在 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)

}

任何帮助深表感谢。谢谢!

4

1 回答 1

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
}
于 2013-02-14T02:14:27.080 回答