-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