Skip to content
Related Articles

Related Articles

Improve Article
Move all digits to the beginning of a given string
  • Last Updated : 03 Jun, 2021

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:

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);
    }
}

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:

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);
    }
}

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
Output: 
1234GeeksforGeeks

 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes




My Personal Notes arrow_drop_up
Recommended Articles
Page :