2
\$\begingroup\$

This is a question from careercup.com. You are given an alphanumeric string. Complete the function sortSegments that will segment the string into substrings of consecutive letters or numbers and then sort the substrings. For example, the string "AZQF013452BAB" will result in "AFQZ012345ABB". The input letters will be uppercase and numbers will be between 0 and 9 inclusive.

#include <iostream>
#include <string>
#include <algorithm>
void sortSegments(std::string& input)
{
 bool toggle1 = isalpha(input[0])? true: false;
 size_t k = 0;
 for(size_t i = 1; i <= input.size(); ++i)
 {
 bool toggle2 = isalpha(input[i])? true: false;
 if(toggle1 != toggle2)
 {
 std::sort(input.begin()+k, input.begin()+i);
 toggle1 = toggle2;
 k=i;
 }
 }
}
int main()
{
 std::string input("AZQKF013452BAB");
 sortSegments(input);
 std::cout << input;
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Sep 11, 2017 at 22:24
\$\endgroup\$
1
  • \$\begingroup\$ As style only improvement - you can make your function to return reference to input to allow calls chaining std::cout << sortSegments(input) << '\n'; \$\endgroup\$ Commented Sep 12, 2017 at 5:22

1 Answer 1

4
\$\begingroup\$

FWIW, your function has a bug.

If you change the input string to "AZQKF013452BAB98", you will notice the problem.

The reason for the bug it that the null character is neither a digit nor an alphabetical character.

Here's an updated version of the function that fixes the bug.

void sortSegments(std::string& input)
{
 bool toggle1 = isalpha(input[0])? true: false;
 size_t k = 0;
 // Change the <= to <
 for(size_t i = 0; i < input.size(); ++i)
 {
 bool toggle2 = isalpha(input[i])? true: false;
 if(toggle1 != toggle2)
 {
 std::sort(input.begin()+k, input.begin()+i);
 toggle1 = toggle2;
 k=i;
 }
 }
 // Sort the remaining characters.
 std::sort(input.begin()+k, input.end());
}
answered Sep 11, 2017 at 22:34
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Why do you need i outside the loop? it should be equal to input.size() when loop exits, or just pass input.end(). I would rewrite it using iterators from the beginning \$\endgroup\$ Commented Sep 12, 2017 at 4:04
  • \$\begingroup\$ @ArtemyVysotsky, good point. \$\endgroup\$ Commented Sep 12, 2017 at 5:08
  • 1
    \$\begingroup\$ your fix is not good - choose begin()+size() or end(). Just size() will not compile \$\endgroup\$ Commented Sep 12, 2017 at 5:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.