【发布时间】: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++,堆栈是完成它的最简单方法