write the function \"ReverseSentence\" that takes a string parameter and changes
ID: 3762218 • Letter: W
Question
write the function "ReverseSentence" that takes a string parameter and changes it, by reversing it. For example: INPUT: the first test OUTPUT: tset tsrif eht The function must not use an extra string, but must reverse the elements of the input string.
/* Lab for function to reverse string */
#include <iostream>
#include <string>
using namespace std;
void ReverseSentence( /* Your Code Here */ ){
/* Body of Function Here */
}
int main(){
string inputSentence;
cout << "Input your sentence: ";
getline(cin, inputSentence);
cout << endl;
ReverseSentence(inputSentence);
cout << "Reversed Sentence:" << endl;
cout << inputSentence << endl;
return 0;
}
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
void ReverseSentence(string &sentence){
/* Body of Function Here */
int len = (int)sentence.length();
int i=0;
int j = len-1;
char c;
while(i<j)
{
c = sentence[i];
sentence[i] = sentence[j];
sentence[j] = c;
i++;
j--;
}
}
int main(){
string inputSentence;
cout << "Input your sentence: ";
getline(cin, inputSentence);
cout << endl;
ReverseSentence(inputSentence);
cout << "Reversed Sentence:" << endl;
cout << inputSentence << endl;
return 0;
}
OP:
Input your sentence: the first test
Reversed Sentence:
tset tsrif eht
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.