-5
反转句子中的每一个字,我有如下句子使用C++需要代码优化我的代码片段
"Where are you going"
我希望每个词应该在一个句子里得到扭转像图所示
"erehW era uoy gniog"
提前致谢。
#include "stdafx.h"
#include "conio.h"
#include <string.h>
#include <iostream>
using namespace std;
//反转功能
void reverse(char* sentence)
{
int hold, index = 0;
//这里我们呼吁while循环
while (index >= 0)
{
//通过句子,直到空终止
while (sentence[index] != ' ')
{
if(sentence[index] == '\0')
break;
index++;
}
hold = index + 1;
index--;
/*
In your original code,
This while loop(below) will continue to keep decrementing index
even below `0`,You wont exit this while loop until you encounter a ` `.
For the 1st word of the sentence you will never come out of the loop.
Hence the check, index>=0
*/
while (index >= 0 && sentence[index] != ' ')
{
cout << sentence[index];
index--;
}
cout<<" ";
index = hold;
if(sentence[hold-1] == '\0')
{
index = -1;
}
}
}
//main function
int main()
{
char* sentence = new char[256];
cin.getline(sentence, 256);
reverse(sentence);
delete[] sentence; // Delete the allocated memory
}
请修复您的代码格式,此问题目前接近无法读取。 – shuttle87
@prakash你为什么认为你需要优化? – LogicStuff
我正在使用这么多循环。它杀死了性能。 – prakash