Open In App

Move all digits to the beginning of a given string

Last Updated : 08 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S, the task is to move all the digits present in the string, to the beginning of the string.

Examples:

Input: S = “Geeks4forGeeks123”
Output: 4123GeeksforGeeks
Explanation:
The given string contains digits 4, 1, 2, and 3. Moving all the digits to the beginning of the string modifies the string to “4123GeeksforGeeks”.

Input: S = “GeeksforGeeks1234 A Com56puter Science Port7al”
Output: 1234567GeeksforGeeks A Computer Science Portal

Approach: The idea is to traverse the string and maintain two strings, one string contains the digits and another string contains non-numeric characters. In the end, append both the strings to the result in the required order.

Below is the implementation of the above approach:

C++




// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to move all the digit
// to the beginning of the string
void moveAllDigitAtBeginning(
  string str)
{
 
  // Calculate the string length
  int len = str.size();
 
  // Stores the digits
  string digits = "";
 
  // Stores the non-numeric character
  string nonNumericCharacter = "";
 
  // Traverse the string and
  // check if there is a digit
  for (int i = 0; i < str.size(); i++)
  {
    char c = str[i];
    // If character is a digit,
    // add it to the string digits
    if (c >= 48 && c <= 57)
    {
      digits += c;
    }
 
    // Otherwise, add it to the
    // string nonNumericCharacter
    else
    {
      nonNumericCharacter += c;
    }
  }
 
 
  // Append both the strings
  digits += nonNumericCharacter;
 
  // Print the string
  cout << digits << endl;
}
 
// Driver Code
int main()
{
  // Given String str
  string str = "GeeksforGeeks123";
  moveAllDigitAtBeginning(str);
  return 0;
}
 
// this code is contributed by harimahecha


Java




// Java program for the above approach
 
class GFG {
 
    // Function to move all the digit
    // to the beginning of the string
    static void moveAllDigitAtBeginning(
        String str)
    {
        // Calculate the string length
        int len = str.length();
 
        // Stores the digits
        StringBuilder digits
            = new StringBuilder();
 
        // Stores the non-numeric character
        StringBuilder nonNumericCharacter
            = new StringBuilder();
 
        // Traverse the string and
        // check if there is a digit
        for (char c : str.toCharArray()) {
 
            // If character is a digit,
            // add it to the string digits
            if (c >= 48 && c <= 57) {
                digits.append(c);
            }
 
            // Otherwise, add it to the
            // string nonNumericCharacter
            else {
                nonNumericCharacter.append(c);
            }
        }
 
        // Append both the strings
        digits.append(
            nonNumericCharacter.toString());
 
        // Print the string
        System.out.print(
            digits.toString() + " ");
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Given String str
        String str
            = "GeeksforGeeks123";
        moveAllDigitAtBeginning(str);
    }
}


Python3




# Python program for the above approach
 
# Function to move all the digit
# to the beginning of the string
def moveAllDigitAtBeginning(str):
    # Calculate the string length
    Len=len(str)
     
    # Stores the digits
    digits=""
     
    # Stores the non-numeric character
    nonNumericCharacter=""
     
    # Traverse the string and
    # check if there is a digit
    for i in range(len(str)):
        c=str[i]
        # If character is a digit,
        # add it to the string digits
        if(ord(c)>=48 and ord(c)<=57):
            digits+=c
         
        # Otherwise, add it to the
        # string nonNumericCharacter
        else:
            nonNumericCharacter+=c
             
    # Append both the strings
    digits+=nonNumericCharacter
     
    # Print the string
    print(digits)
     
# Driver Code
 
# Given String str
str="GeeksforGeeks123"
moveAllDigitAtBeginning(str)
 
# This code is contributed by Aman Kumar


C#




// C# program for the above approach
using System;
 
public class GFG{
 
// Function to move all the digit
// to the beginning of the string
static void moveAllDigitAtBeginning(string str)
{
 
// Calculate the string length
int len = str.Length;
 
// Stores the digits
string digits = "";
 
// Stores the non-numeric character
string nonNumericCharacter = "";
 
// Traverse the string and
// check if there is a digit
for (int i = 0; i < str.Length; i++)
{
    char c = str[i];
    // If character is a digit,
    // add it to the string digits
    if (c >= 48 && c <= 57)
    {
    digits += c;
    }
 
    // Otherwise, add it to the
    // string nonNumericCharacter
    else
    {
    nonNumericCharacter += c;
    }
}
 
 
// Append both the strings
digits += nonNumericCharacter;
 
// Print the string
Console.WriteLine(digits);
}
 
// Driver Code
static public void Main ()
{
// Given String str
string str = "GeeksforGeeks123";
moveAllDigitAtBeginning(str);
}
 
}
 
// this code is contributed by Pushpesh Raj.


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to move all the digit
// to the beginning of the string
function moveAllDigitAtBeginning(str)
{
     
    // Calculate the string length
    var len = str.length;
     
    // Stores the digits
    var digits = [];
     
    // Stores the non-numeric character
    var nonNumericCharacter = [];
     
    // Traverse the string and
    // check if there is a digit
    var temp = str.split("");
    for(const c of temp)
    {
         
        // If character is a digit,
        // add it to the string digits
        if (c.charCodeAt(0) >= 48 &&
            c.charCodeAt(0) <= 57)
        {
            digits.push(c);
        }
     
        // Otherwise, add it to the
        // string nonNumericCharacter
        else
        {
            nonNumericCharacter.push(c);
        }
    }
     
    // Append both the strings
    digits.push(nonNumericCharacter.join(""));
     
    // Print the string
    document.write(digits.join("") + " ");
}
 
// Driver Code
 
// Given String str
var str = "GeeksforGeeks123";
moveAllDigitAtBeginning(str);
 
// This code is contributed by rdtank
 
</script>


Output: 

123GeeksforGeeks

 

Time Complexity: O(N)
Auxiliary Space: O(1)

Regular Expression based Approach: The given problem can also be solved using Regular Expression and replace all non-numeric characters with the empty string (“ “) that give you all numbers and replace all digits with the empty string (“ “) that gives you all non-numeric characters. In the end, concatenate the string and print the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <iostream>
#include <string>
#include <regex>
using namespace std;
 
// Function to move all the digit
// at the beginning of the string
void moveAllDigitAtBeginning(string str)
{
    // Replace all the non-numeric
    // characters with " " and
    // replace all digits with " "
    string moveAllDigit =
        regex_replace(str, regex("\\D+"), "")
        + regex_replace(str, regex("\\d"), "");
   
    // Print the string
    cout << moveAllDigit;
}
   
// Driver Code
int main()
{
    // Given String str
    string str = "GeeksforGeeks1234";
    moveAllDigitAtBeginning(str);
    return 0;
}
// This code is contributed by akashish__


Java




// Java program for the above approach
 
class GFG {
 
    // Function to move all the digit
    // at the beginning of the string
    static void moveAllDigitAtBeginning(
        String str)
    {
        // Replace all the non-numeric
        // characters with " " and
        // replace all digits with " "
        String moveAllDigit = str.replaceAll("\\D+", "")
                              + str.replaceAll("\\d+", "");
 
        // Print the string
        System.out.println(moveAllDigit);
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Given String str
        String str
            = "GeeksforGeeks1234";
        moveAllDigitAtBeginning(str);
    }
}


Python3




import re
 
# Function to move all the digit
# at the beginning of the string
def moveAllDigitAtBeginning(str):
   
    # Replace all the non-numeric
    # characters with "" and
    # replace all digits with ""
    moveAllDigit = re.sub(r'\D+',"", str) + re.sub(r'\d+',"", str)
 
    # Print the string
    print(moveAllDigit)
 
# Driver Code
if __name__ == "__main__":
   
    # Given String str
    str = "GeeksforGeeks1234"
    moveAllDigitAtBeginning(str)
     
# This code is contributed by divyansh2212


C#




// C# program for the above approach
using System;
using System.Text.RegularExpressions;
public class GFG
{
 
    // Function to move all the digit
    // at the beginning of the string
    static void moveAllDigitAtBeginning(
        String str)
    {
       
        // Replace all the non-numeric
        // characters with " " and
        // replace all digits with " "
        String moveAllDigit = Regex.Replace(str, "\\D+", "")
            +Regex.Replace(str, "\\d", "");
       
        // Print the string
        Console.WriteLine(moveAllDigit);
    }
 
    // Driver Code
    public static void Main(String []args)
    {
       
        // Given String str
        String str
            = "GeeksforGeeks1234";
        moveAllDigitAtBeginning(str);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




// Function to move all the digit
// at the beginning of the string
function moveAllDigitAtBeginning(str) {
    // Replace all the non-numeric
    // characters with "" and
    // replace all digits with ""
    let moveAllDigit = str.replace(/\D+/g, "") + str.replace(/\d+/g, "");
    // Print the string
    console.log(moveAllDigit);
}
 
// Driver Code
let str = "GeeksforGeeks1234";
moveAllDigitAtBeginning(str);
// contributed by akashish__


Output: 

1234GeeksforGeeks

 

Time Complexity: O(N)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads