【问题标题】:Flips individual words in a sentence in C?翻转C中句子中的单个单词?
【发布时间】:2013-01-29 18:30:51
【问题描述】:

我正在尝试翻转 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)

}

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

【问题讨论】:

  • 你可以将字符串拆分,存储在数组中,然后从更高的索引打印值
  • 您应该在此处显示您的代码并就特定问题提出特定问题。从算法上讲,您可以反转每个单词,然后反转整个字符串。
  • 很抱歉。我现在修复了我的代码以显示我的问题。
  • @IswantoSan 或...使用堆栈
  • @James,我同意,如果您使用 C++,堆栈是完成它的最简单方法

标签: c loops flip words


【解决方案1】:

您在增加 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
}

【讨论】:

    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多