用C翻译句子中的单个单词?

时间:2013-02-14 02:00:02

标签: c loops flip words

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

}

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

您正在与lengthPlacer变量同时递增pos变量。你需要一个内部循环首先递增直到空格,然后循环才能反转。

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
}
相关问题