# Move all digits to the beginning of a given string

In this article, we will explore a common string manipulation problem: moving all digits to the beginning of a given string. This task is often seen in data cleaning or preprocessing, where we need to standardize or reformat strings in a certain way. To tackle this problem, we'll use C++, a widely-used programming language celebrated for its efficiency and control.

## Problem Statement

Given a string that contains alphanumeric characters, our task is to move all the digits present in the string to the beginning, while keeping the order of the rest of the characters the same.

## Solution Approach

Our approach to solving this problem involves two key steps −

• Separate Digits and Non-digits  Traverse the string from left to right, appending all digits to a 'digits' string and all non-digits to a 'nonDigits' string.

• Concatenate Strings  Combine the 'digits' and 'nonDigits' strings, ensuring that the digits are at the beginning.

### Example

Below is the C++ code for our problem −

#include <bits/stdc++.h>
using namespace std;

// Function to move all digits to the beginning of a string
string moveDigits(string str) {
string digits = "", nonDigits = "";

for (char c : str) {
if (isdigit(c))
digits += c;
else
nonDigits += c;
}

return digits + nonDigits;
}

int main() {
string str = "abc123def456";

string result = moveDigits(str);
cout << "String after moving digits to the beginning: " << result << endl;

return 0;
}


### Output

String after moving digits to the beginning: 123456abcdef


## Explanation

Let's consider the string −

str = "abc123def456"

After separating the digits and non-digits, we get:

digits = "123456", nonDigits = "abcdef"

By concatenating these two strings (digits first), we obtain the result:

result = "123456abcdef"

## Conclusion

The task of moving all digits to the beginning of a string is a useful exercise for learning string manipulation in C++. It provides valuable insights into how we can traverse and modify strings based on certain conditions.

Updated on: 18-May-2023

51 Views 