如何在 C++ 中反转给定的句子(字符串)?
示例:如果输入是 DOGS LIKE CATS 输出 - CATS LIKE DOGS
认为我必须仅使用:If-else 条件,而 & for 循环、数组、字符串和函数。 NOT 字符串函数、指针和函数动态内存分配&结构。 空格也需要与示例相同。
我尝试执行以下操作,但它不起作用,你能帮忙吗?
void revSent(char str[]){
char temp[100];
int k;
for (i=sentenceSize ; i>0 ; i--)
for (k=0 ; k<sentenceSize ; k++)
temp[k]=str[i];
for (k=0 ; k<sentenceSize ; k++)
if (temp[k]!=' ')
for (i=k ; i>0 ; i--)
printf("%c", temp[i]);
}
Example: if the input was DOGS LIKE CATS
output- CATS LIKE DOGS
consider that I have to use only : If-else conditions, while & for loops, Arrays, strings and Functions. NOT strings functions, Pointers & Dynamic memory allocation & structures.
Spaces need to be the same as the example as well.
I tried to do the following but it doesnt work can you help please?
void revSent(char str[]){
char temp[100];
int k;
for (i=sentenceSize ; i>0 ; i--)
for (k=0 ; k<sentenceSize ; k++)
temp[k]=str[i];
for (k=0 ; k<sentenceSize ; k++)
if (temp[k]!=' ')
for (i=k ; i>0 ; i--)
printf("%c", temp[i]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
就地执行此操作很容易,无需任何额外的数据结构:
反转整个字符串:
DOGS LIKE CATS
->STAC EKIL SGOD
反转字符串中的每个单词:
STAC EKIL SGOD
->喜欢猫
DOGS
提示:您可以对 (1) 和 (2) 使用相同的函数。
It's easy to do this in-place, without any additional data structures:
reverse the whole string:
DOGS LIKE CATS
->STAC EKIL SGOD
reverse each word in the string:
STAC EKIL SGOD
->CATS LIKE
DOGS
Hint: you can use the same function for both (1) and (2).
您可以实施以下方法来找到解决方案:
You could implement the following to arrive at a solution:
如果您将单词定义为空格分隔的标记,则可以执行以下操作:
本质上,您希望从单词的定义开始,然后将单词放入容器中,最后使用 std::reverse() 来反转它们。
对于算法作业,你的老师可能不会对此感到满意。您想要创建一个将句子拆分为单词的函数。当然,您可以在同一字符串中使用指针——这很可能是您的讲师的意图,但如果这不是您必须做的,那么我个人发现使用容器更容易。
If you define a word as a whitespace-delimited token then the following will do:
In essence you want to start with the definition of a word, then place in a container your words, and finally use
std::reverse()
to reverse them.For an algorithms homework your instructor probably won't be satisfied with this. You want to create a function that splits a sentence into words. You can, of course, work with pointers within the same string -- and that may well be the intent of your instructor, but if that isn't what you must then I personally find working with a container easier.
我给出一个提示:因为你不能使用数据结构,所以你不能直接使用 Paul 或 OJ 的方法。但是,递归函数调用会形成堆栈。
I'll give a hint: since you can't use data structures you can't directly use Paul or OJ's method. BUT, recursive function calling would form a stack.
瞧!
Voila!
谁说STL没有用?
根据您的操作方式,可以采用不同的方法来解决此问题。
我的方法就是:
这是C++解决方案(使用 find 和 substr,两个非常有用的字符串函数)
who says the STL isn't useful?
Depending on how you do this, there are different ways to attack this.
my way is just:
Here's the C++ solution (using find and substr, two very useful string functions)