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
Can I intentionally omit previous work experience or pretend it doesn't exist when applying for jobs?
Is Arc Length always irrational between two rational points?
Machine learning and operations research projects
Email about missed connecting flight compensation 5 months after flight, is there a point?
Is it rude to tell recruiters I would only change jobs for a better salary?
Where is the USB2 OTG port on the RPi 4 Model B located?
During copyediting, journal disagrees about spelling of paper's main topic
Why does Hellboy file down his horns?
How can an advanced civilization forget how to manufacture its technology?
How do Windows version numbers work?
Why isn't there research to build a standard lunar, or Martian mobility platform?
Is it possible for thermophilic viruses to infect humans?
Can I call 112 to check a police officer's identity in the Czech Republic?
Are neural networks prone to catastrophic forgetting?
When did the Roman Empire fall according to contemporaries?
Why does the autopilot disengage even when it does not receive pilot input?
Extract an attribute value from XML
Were there any new Pokémon introduced in the movie Pokémon: Detective Pikachu?
Is Prophet from Facebook any different from a linear regression?
Is this floating-point optimization allowed?
Who Can Help Retag This?
I have a ruthless DM and I'm considering leaving the party. What are my options to minimize the negative impact to the rest of the group?
Robbers: The Hidden OEIS Substring
Creating custom objects with custom properties using generics
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
$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
$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
10 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
$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
New contributor
edited 9 hours ago
200_success
134k21 gold badges171 silver badges441 bronze badges
134k21 gold badges171 silver badges441 bronze badges
New contributor
asked 10 hours ago
JarrydJarryd
1162 bronze badges
1162 bronze badges
New contributor
New contributor
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
10 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
10 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
10 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
10 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$
$begingroup$
Love that. Now if only if we had reverse ranges so we could use the range based for.
$endgroup$
– Martin York
38 mins ago
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
$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 9 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$
$begingroup$
Love that. Now if only if we had reverse ranges so we could use the range based for.
$endgroup$
– Martin York
38 mins ago
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$
$begingroup$
Love that. Now if only if we had reverse ranges so we could use the range based for.
$endgroup$
– Martin York
38 mins ago
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 1 hour ago
Jerry CoffinJerry Coffin
29.5k4 gold badges62 silver badges131 bronze badges
29.5k4 gold badges62 silver badges131 bronze badges
$begingroup$
Love that. Now if only if we had reverse ranges so we could use the range based for.
$endgroup$
– Martin York
38 mins ago
add a comment |
$begingroup$
Love that. Now if only if we had reverse ranges so we could use the range based for.
$endgroup$
– Martin York
38 mins ago
$begingroup$
Love that. Now if only if we had reverse ranges so we could use the range based for.
$endgroup$
– Martin York
38 mins ago
$begingroup$
Love that. Now if only if we had reverse ranges so we could use the range based for.
$endgroup$
– Martin York
38 mins ago
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
$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
$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
$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
New contributor
answered 1 hour ago
Marek RMarek R
1011 bronze badge
1011 bronze badge
New contributor
New contributor
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
10 hours ago