Reverse The String Whenever Digit Is Encountered In C++ - C++ Programming Tutorial
C++ Course / Strings / Reverse The String Whenever Digit Is Encountered In C++

Reverse The String Whenever Digit Is Encountered In C++

BLUF: Mastering Reverse The String Whenever Digit Is Encountered In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Reverse The String Whenever Digit Is Encountered In C++

C++ is renowned for its efficiency. Learn how Reverse The String Whenever Digit Is Encountered In C++ enables low-level control and high-performance computing in the tutorial below.

In this tutorial, we will explore the process of reversing a string in C++ whenever a digit is encountered.

Problem Statement

The task involves reversing sections of a string each time a digit is encountered within the section. Essentially, any segment between digits should be flipped. The digits themselves act as separators, not subject to reversal. For example, given the input string "abc1def2ghi3jkl", the desired output would be "cba1fed2ihg3lkj".

Introduction:

Working with strings is a fundamental concept in programming, essential for tasks like text processing, data validation, and formatting. This particular challenge combines string manipulation with conditional statements, making it an ideal exercise for mastering string operations and character iteration.

History:

Ever since its establishment, the field of computer science has been deeply rooted in the practice of string manipulation. Within C++, the Standard Template Library (STL) offers a robust collection of functionalities designed specifically for handling strings, streamlining various tasks in the process. The concept of reversing strings dates back to early algorithms used for tasks such as text editing and data serialization.

Approach:

We will do this by:

  • Traversing the string, we take up characters until we reach a digit.
  • Appending the collected characters after they have been reversed to a result string.
  • Adding the digit itself without changing it into a result string.
  • And repeating this procedure until all parts are processed completely.
  • Implementation in C++

Here is the C++ code that presents the solution:

Example

#include <iostream>
#include <string>
#include <algorithm> // for reverse

std::string reverseSegments(const std::string &input) {
    std::string result;
    std::string segment;

    for (char ch : input) {
        if (isdigit(ch)) {
            // Reverse the current segment and add to result
            std::reverse(segment.begin(), segment.end());
            result += segment;
            // Append the digit to result
            result += ch;
            // Clear the segment for next set of characters
            segment.clear();
        } else {
            // Collect the characters in the segment
            segment += ch;
        }
    }

    // Reverse and append any remaining segment after the last digit
    std::reverse(segment.begin(), segment.end());
    result += segment;

    return result;
}

int main() {
    std::string input = "abc1def2ghi3jkl";
    std::string output = reverseSegments(input);
    std::cout << "Input: " << input << std::endl;
    std::cout << "Output: " << output << std::endl;
    return 0;
}

Output:

Output

Input: abc1def2ghi3jkl
Output: cba1fed2ihg3lkj

Explanation:

  • Libraries Used: <iostream> for input and output operations. <string> for string handling. <algorithm> for the std::reverse function.
  • Function reverseSegments: A constant reference of a string is taken as an input into it. The two strings are initialized as a result to store the final output while segmenting for collecting characters lying between digits. Each character in the input string is gone through. When a digit is encountered, (isdigit(ch)) , we reverse the accumulated part of a segment add the digit and then put it inside a string that contains other non-digit values to get the total reversed segments of that number in outport together with all other non-digit values around it before reversing it again. In order to make its next accumulation easier, we have cleared this part again after each addition or reversal. Whereas any remaining characters in the segment are reversed and appended to result in the end loop.
  • Main Function: Defines the input string. Calls reverseSegments to process the input string. Outputs the original and processed strings.
  • <iostream> for input and output operations.
  • <string> for string handling.
  • <algorithm> for the std::reverse function.
  • A constant reference of a string is taken as an input into it.
  • The two strings are initialized as a result to store the final output while segmenting for collecting characters lying between digits.
  • Each character in the input string is gone through.
  • When a digit is encountered, (isdigit(ch)) , we reverse the accumulated part of a segment add the digit and then put it inside a string that contains other non-digit values to get the total reversed segments of that number in outport together with all other non-digit values around it before reversing it again.
  • In order to make its next accumulation easier, we have cleared this part again after each addition or reversal.
  • Whereas any remaining characters in the segment are reversed and appended to result in the end loop.
  • Defines the input string.
  • Calls reverseSegments to process the input string.
  • Outputs the original and processed strings.
  • Complexity Analysis:

Time Complexity:

  • Time complexity is determined by how much work is done on each element of some text. It also includes changing places i.e., reversing all items in given segments where necessary.
  • Traversal of the string: The program iterates through each character of the input string once. It runs O(n) times where n represents length all characters constituting this sequence.
  • Reversing segments: The std::reverse function is called multiple times throughout the traversal. In the worst case, each character may need to be reversed once. The cumulative time for all reversals is O(n), as each character is part of a segment that is reversed once.
  • Combining these, the overall time complexity is: O(n)+O(n)=O(n)

Space Complexity:

The space complexity is determined by the additional space used for storing intermediate data:

  • Result string: The result string stores the final output, which in the worst case, has the same length as the input string. It requires O(n) space complexity.
  • Segment string: The segment string temporarily holds characters between digits. In the worst case, if there are no digits, this string could hold all n characters of the input string at once. Therefore, it requires O(n) space as well.
  • Additional variables: There are a few additional variables (ch, input, output), but their space usage is negligible compared to the strings.
  • Combining these, the overall space complexity is: O(n)+O(n)=O(n).
  • Conclusion:

In summary, the C++ code showcased here illustrates a hands-on method for altering strings according to defined criteria, such as reversing segments between numerical characters. Leveraging STL features such as std::reverse streamlines the coding process, guaranteeing that the logic is not only effective but also straightforward to comprehend. This scenario serves as a prime illustration of merging string manipulation with conditional statements, showcasing the adaptability and robustness of C++ when managing intricate text processing operations.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience