Reverse the word order in string, without reversing the wordsReverse a string without the <string.h> headerReversing words in a stringReverse a string word by wordVariadic template data pack strucuture designed for debug/trace log (variable-sized records)Reverse the character order of the words in a stringReverse string in JavaScript without using reverse()Order line reversing (reversing line order)Reversing the words order of a stringReverse words in a string without affecting spaceReverse the word in a string with the same order in javascript
How to achieve this rough borders and stippled illustration look?
Stuck Apple Mail - how to reset?
Why do players in the past play much longer tournaments than today's top players?
Is an acid a salt or not?
Professor falsely accusing me of cheating in a class he does not teach, two months after end of the class. What precautions should I take?
What's the point of this scene involving Flash Thompson at the airport?
Why did my rum cake turn black?
Cubic programming and beyond?
Is this floating-point optimization allowed?
Can I use "candidate" as a verb?
What's the minimum number of sensors for a hobby GPS waypoint-following UAV?
diff shows a file that does not exist
Was adding milk to tea started to reduce employee tea break time?
Where is the USB2 OTG port on the RPi 4 Model B located?
What would be the ideal melee weapon made of "Phase Metal"?
Who Can Help Retag This?
Can I intentionally omit previous work experience or pretend it doesn't exist when applying for jobs?
Are randomly-generated passwords starting with "a" less secure?
Were there any new Pokémon introduced in the movie Pokémon: Detective Pikachu?
Replacements for swear words
Why are Hobbits so fond of mushrooms?
What's a moment that's more impactful on a reread called?
Why is dry soil hydrophobic? Bad gardener paradox
Crowbar circuit causes unexpected behavior for op amp circuit
Reverse the word order in string, without reversing the words
Reverse a string without the <string.h> headerReversing words in a stringReverse a string word by wordVariadic template data pack strucuture designed for debug/trace log (variable-sized records)Reverse the character order of the words in a stringReverse string in JavaScript without using reverse()Order line reversing (reversing line order)Reversing the words order of a stringReverse words in a string without affecting spaceReverse the word in a string with the same order in javascript
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
I was tasked with using C++ to turn this:
"Hello Jarryd, do you like socks?"
into:
"socks? like you do Jarryd, Hello";
Here's what I came up with, knocked up in Visual Studio using the TestExplorer to run it. Criticism is much appreciated!
int SentenceFlip::FlipSentenceInPlace(char in_Sentence[])
int index = 0;
int length = strlen(in_Sentence);
while (index < length)
int dist = 0;
int wordSize = 0;
//Get the characters to the first word
for (int i = length - 1; i > 0; i--)
if (in_Sentence[i] == ' ' && i != length - 1)
dist = i - index;
wordSize = length - i - 1; //exclude the space
break;
//Push everything forwards
for (int i = 0; i <= dist; i++)
Move(index, in_Sentence);
//This leaves a space at the end, push it forward
if (index + wordSize >= length)
return 0;
for (size_t i = 0; i < length - wordSize - index - 1; i++)
Move(index + wordSize, in_Sentence);
index += wordSize + 1; //include the space
return -1;
void SentenceFlip::Move(int in_StartIndex, char in_String[])
char temp = in_String[in_StartIndex];
int length = strlen(in_String);
for (int j = length - 1; j >= in_StartIndex; j--)
char temp2 = in_String[j];
in_String[j] = temp;
temp = temp2;
c++ strings
New contributor
Jarryd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
$begingroup$
I was tasked with using C++ to turn this:
"Hello Jarryd, do you like socks?"
into:
"socks? like you do Jarryd, Hello";
Here's what I came up with, knocked up in Visual Studio using the TestExplorer to run it. Criticism is much appreciated!
int SentenceFlip::FlipSentenceInPlace(char in_Sentence[])
int index = 0;
int length = strlen(in_Sentence);
while (index < length)
int dist = 0;
int wordSize = 0;
//Get the characters to the first word
for (int i = length - 1; i > 0; i--)
if (in_Sentence[i] == ' ' && i != length - 1)
dist = i - index;
wordSize = length - i - 1; //exclude the space
break;
//Push everything forwards
for (int i = 0; i <= dist; i++)
Move(index, in_Sentence);
//This leaves a space at the end, push it forward
if (index + wordSize >= length)
return 0;
for (size_t i = 0; i < length - wordSize - index - 1; i++)
Move(index + wordSize, in_Sentence);
index += wordSize + 1; //include the space
return -1;
void SentenceFlip::Move(int in_StartIndex, char in_String[])
char temp = in_String[in_StartIndex];
int length = strlen(in_String);
for (int j = length - 1; j >= in_StartIndex; j--)
char temp2 = in_String[j];
in_String[j] = temp;
temp = temp2;
c++ strings
New contributor
Jarryd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
3
$begingroup$
Welcome to code review. We can do a better job of reviewing your code if you provide the entire SentenceFlip class and the main program.
$endgroup$
– pacmaninbw
9 hours ago
add a comment |
$begingroup$
I was tasked with using C++ to turn this:
"Hello Jarryd, do you like socks?"
into:
"socks? like you do Jarryd, Hello";
Here's what I came up with, knocked up in Visual Studio using the TestExplorer to run it. Criticism is much appreciated!
int SentenceFlip::FlipSentenceInPlace(char in_Sentence[])
int index = 0;
int length = strlen(in_Sentence);
while (index < length)
int dist = 0;
int wordSize = 0;
//Get the characters to the first word
for (int i = length - 1; i > 0; i--)
if (in_Sentence[i] == ' ' && i != length - 1)
dist = i - index;
wordSize = length - i - 1; //exclude the space
break;
//Push everything forwards
for (int i = 0; i <= dist; i++)
Move(index, in_Sentence);
//This leaves a space at the end, push it forward
if (index + wordSize >= length)
return 0;
for (size_t i = 0; i < length - wordSize - index - 1; i++)
Move(index + wordSize, in_Sentence);
index += wordSize + 1; //include the space
return -1;
void SentenceFlip::Move(int in_StartIndex, char in_String[])
char temp = in_String[in_StartIndex];
int length = strlen(in_String);
for (int j = length - 1; j >= in_StartIndex; j--)
char temp2 = in_String[j];
in_String[j] = temp;
temp = temp2;
c++ strings
New contributor
Jarryd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
I was tasked with using C++ to turn this:
"Hello Jarryd, do you like socks?"
into:
"socks? like you do Jarryd, Hello";
Here's what I came up with, knocked up in Visual Studio using the TestExplorer to run it. Criticism is much appreciated!
int SentenceFlip::FlipSentenceInPlace(char in_Sentence[])
int index = 0;
int length = strlen(in_Sentence);
while (index < length)
int dist = 0;
int wordSize = 0;
//Get the characters to the first word
for (int i = length - 1; i > 0; i--)
if (in_Sentence[i] == ' ' && i != length - 1)
dist = i - index;
wordSize = length - i - 1; //exclude the space
break;
//Push everything forwards
for (int i = 0; i <= dist; i++)
Move(index, in_Sentence);
//This leaves a space at the end, push it forward
if (index + wordSize >= length)
return 0;
for (size_t i = 0; i < length - wordSize - index - 1; i++)
Move(index + wordSize, in_Sentence);
index += wordSize + 1; //include the space
return -1;
void SentenceFlip::Move(int in_StartIndex, char in_String[])
char temp = in_String[in_StartIndex];
int length = strlen(in_String);
for (int j = length - 1; j >= in_StartIndex; j--)
char temp2 = in_String[j];
in_String[j] = temp;
temp = temp2;
c++ strings
c++ strings
New contributor
Jarryd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Jarryd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 8 hours ago
200_success
134k21 gold badges171 silver badges441 bronze badges
134k21 gold badges171 silver badges441 bronze badges
New contributor
Jarryd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked 9 hours ago
JarrydJarryd
1112 bronze badges
1112 bronze badges
New contributor
Jarryd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Jarryd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
$begingroup$
Welcome to code review. We can do a better job of reviewing your code if you provide the entire SentenceFlip class and the main program.
$endgroup$
– pacmaninbw
9 hours ago
add a comment |
3
$begingroup$
Welcome to code review. We can do a better job of reviewing your code if you provide the entire SentenceFlip class and the main program.
$endgroup$
– pacmaninbw
9 hours ago
3
3
$begingroup$
Welcome to code review. We can do a better job of reviewing your code if you provide the entire SentenceFlip class and the main program.
$endgroup$
– pacmaninbw
9 hours ago
$begingroup$
Welcome to code review. We can do a better job of reviewing your code if you provide the entire SentenceFlip class and the main program.
$endgroup$
– pacmaninbw
9 hours ago
add a comment |
3 Answers
3
active
oldest
votes
$begingroup$
Your algorithm is supremely inefficient. Moving a word to the front moves all the other characters to the back, resulting in a quadratic algorithm. In addition to that, you repeatedly recalculate the length of the null terminated string.
As an aside, the standard library provides std::rotate() for moving part of a sequence from the end to the beginning, no need to write your own.
There is an alternative in-place algorithm which swaps every character at most twice, and traverses two additional times. Thus it is trivially proven linear:
- Reverse everything.
- Reverse every word in isolation.
The standard library features std::reverse() for implementing this.
$endgroup$
add a comment |
$begingroup$
I would probably do this by reading the words into a vector of strings, then rather than reversing the order, just traverse the vector in reverse order:
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
int main()
std::vector<std::string> words std::istream_iterator<std::string>(std::cin), ;
std::copy(words.rbegin(), words.rend(),
std::ostream_iterator<std::string>(std::cout, " "));
std::cout << 'n';
So a couple obvious points:
- Avoiding work is good.
- Letting your code avoid work is good too.
- The standard library has lots of stuff that can make programming a lot easier.
$endgroup$
add a comment |
$begingroup$
This quite simple task.
Just find words in reverse order and put them in new string.
Code should be quite simple:
std::string reverse_words(std::string_view s)
std::string result;
result.reserve(s.size());
while(!s.empty())
auto i = s.rfind(' ');
result.append(s.begin() + i + 1, s.end());
if (i == std::string_view::npos) break;
result += ' ';
s = s.substr(0, i);
return result;
This code is fast since it does minimum allocations and minimum amount of coping.
https://wandbox.org/permlink/bYmojDyt0Z0xMJv0
New contributor
Marek R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Jarryd is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f224031%2freverse-the-word-order-in-string-without-reversing-the-words%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Your algorithm is supremely inefficient. Moving a word to the front moves all the other characters to the back, resulting in a quadratic algorithm. In addition to that, you repeatedly recalculate the length of the null terminated string.
As an aside, the standard library provides std::rotate() for moving part of a sequence from the end to the beginning, no need to write your own.
There is an alternative in-place algorithm which swaps every character at most twice, and traverses two additional times. Thus it is trivially proven linear:
- Reverse everything.
- Reverse every word in isolation.
The standard library features std::reverse() for implementing this.
$endgroup$
add a comment |
$begingroup$
Your algorithm is supremely inefficient. Moving a word to the front moves all the other characters to the back, resulting in a quadratic algorithm. In addition to that, you repeatedly recalculate the length of the null terminated string.
As an aside, the standard library provides std::rotate() for moving part of a sequence from the end to the beginning, no need to write your own.
There is an alternative in-place algorithm which swaps every character at most twice, and traverses two additional times. Thus it is trivially proven linear:
- Reverse everything.
- Reverse every word in isolation.
The standard library features std::reverse() for implementing this.
$endgroup$
add a comment |
$begingroup$
Your algorithm is supremely inefficient. Moving a word to the front moves all the other characters to the back, resulting in a quadratic algorithm. In addition to that, you repeatedly recalculate the length of the null terminated string.
As an aside, the standard library provides std::rotate() for moving part of a sequence from the end to the beginning, no need to write your own.
There is an alternative in-place algorithm which swaps every character at most twice, and traverses two additional times. Thus it is trivially proven linear:
- Reverse everything.
- Reverse every word in isolation.
The standard library features std::reverse() for implementing this.
$endgroup$
Your algorithm is supremely inefficient. Moving a word to the front moves all the other characters to the back, resulting in a quadratic algorithm. In addition to that, you repeatedly recalculate the length of the null terminated string.
As an aside, the standard library provides std::rotate() for moving part of a sequence from the end to the beginning, no need to write your own.
There is an alternative in-place algorithm which swaps every character at most twice, and traverses two additional times. Thus it is trivially proven linear:
- Reverse everything.
- Reverse every word in isolation.
The standard library features std::reverse() for implementing this.
answered 8 hours ago
DeduplicatorDeduplicator
13.1k20 silver badges55 bronze badges
13.1k20 silver badges55 bronze badges
add a comment |
add a comment |
$begingroup$
I would probably do this by reading the words into a vector of strings, then rather than reversing the order, just traverse the vector in reverse order:
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
int main()
std::vector<std::string> words std::istream_iterator<std::string>(std::cin), ;
std::copy(words.rbegin(), words.rend(),
std::ostream_iterator<std::string>(std::cout, " "));
std::cout << 'n';
So a couple obvious points:
- Avoiding work is good.
- Letting your code avoid work is good too.
- The standard library has lots of stuff that can make programming a lot easier.
$endgroup$
add a comment |
$begingroup$
I would probably do this by reading the words into a vector of strings, then rather than reversing the order, just traverse the vector in reverse order:
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
int main()
std::vector<std::string> words std::istream_iterator<std::string>(std::cin), ;
std::copy(words.rbegin(), words.rend(),
std::ostream_iterator<std::string>(std::cout, " "));
std::cout << 'n';
So a couple obvious points:
- Avoiding work is good.
- Letting your code avoid work is good too.
- The standard library has lots of stuff that can make programming a lot easier.
$endgroup$
add a comment |
$begingroup$
I would probably do this by reading the words into a vector of strings, then rather than reversing the order, just traverse the vector in reverse order:
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
int main()
std::vector<std::string> words std::istream_iterator<std::string>(std::cin), ;
std::copy(words.rbegin(), words.rend(),
std::ostream_iterator<std::string>(std::cout, " "));
std::cout << 'n';
So a couple obvious points:
- Avoiding work is good.
- Letting your code avoid work is good too.
- The standard library has lots of stuff that can make programming a lot easier.
$endgroup$
I would probably do this by reading the words into a vector of strings, then rather than reversing the order, just traverse the vector in reverse order:
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
int main()
std::vector<std::string> words std::istream_iterator<std::string>(std::cin), ;
std::copy(words.rbegin(), words.rend(),
std::ostream_iterator<std::string>(std::cout, " "));
std::cout << 'n';
So a couple obvious points:
- Avoiding work is good.
- Letting your code avoid work is good too.
- The standard library has lots of stuff that can make programming a lot easier.
answered 38 mins ago
Jerry CoffinJerry Coffin
29.5k4 gold badges62 silver badges131 bronze badges
29.5k4 gold badges62 silver badges131 bronze badges
add a comment |
add a comment |
$begingroup$
This quite simple task.
Just find words in reverse order and put them in new string.
Code should be quite simple:
std::string reverse_words(std::string_view s)
std::string result;
result.reserve(s.size());
while(!s.empty())
auto i = s.rfind(' ');
result.append(s.begin() + i + 1, s.end());
if (i == std::string_view::npos) break;
result += ' ';
s = s.substr(0, i);
return result;
This code is fast since it does minimum allocations and minimum amount of coping.
https://wandbox.org/permlink/bYmojDyt0Z0xMJv0
New contributor
Marek R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
$begingroup$
This quite simple task.
Just find words in reverse order and put them in new string.
Code should be quite simple:
std::string reverse_words(std::string_view s)
std::string result;
result.reserve(s.size());
while(!s.empty())
auto i = s.rfind(' ');
result.append(s.begin() + i + 1, s.end());
if (i == std::string_view::npos) break;
result += ' ';
s = s.substr(0, i);
return result;
This code is fast since it does minimum allocations and minimum amount of coping.
https://wandbox.org/permlink/bYmojDyt0Z0xMJv0
New contributor
Marek R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
$begingroup$
This quite simple task.
Just find words in reverse order and put them in new string.
Code should be quite simple:
std::string reverse_words(std::string_view s)
std::string result;
result.reserve(s.size());
while(!s.empty())
auto i = s.rfind(' ');
result.append(s.begin() + i + 1, s.end());
if (i == std::string_view::npos) break;
result += ' ';
s = s.substr(0, i);
return result;
This code is fast since it does minimum allocations and minimum amount of coping.
https://wandbox.org/permlink/bYmojDyt0Z0xMJv0
New contributor
Marek R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
This quite simple task.
Just find words in reverse order and put them in new string.
Code should be quite simple:
std::string reverse_words(std::string_view s)
std::string result;
result.reserve(s.size());
while(!s.empty())
auto i = s.rfind(' ');
result.append(s.begin() + i + 1, s.end());
if (i == std::string_view::npos) break;
result += ' ';
s = s.substr(0, i);
return result;
This code is fast since it does minimum allocations and minimum amount of coping.
https://wandbox.org/permlink/bYmojDyt0Z0xMJv0
New contributor
Marek R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Marek R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered 36 mins ago
Marek RMarek R
1011 bronze badge
1011 bronze badge
New contributor
Marek R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Marek R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
add a comment |
Jarryd is a new contributor. Be nice, and check out our Code of Conduct.
Jarryd is a new contributor. Be nice, and check out our Code of Conduct.
Jarryd is a new contributor. Be nice, and check out our Code of Conduct.
Jarryd is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f224031%2freverse-the-word-order-in-string-without-reversing-the-words%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
$begingroup$
Welcome to code review. We can do a better job of reviewing your code if you provide the entire SentenceFlip class and the main program.
$endgroup$
– pacmaninbw
9 hours ago