Monday, January 6, 2025
Google search engine
HomeData Modelling & AIMove all digits to the beginning of a given string

Move all digits to the beginning of a given string

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: 4123neveropen
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 “4123neveropen”.

Input: S = “neveropen1234 A Com56puter Science Port7al”
Output: 1234567neveropen 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 = "neveropen123";
  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
            = "neveropen123";
        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="neveropen123"
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 = "neveropen123";
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 = "neveropen123";
moveAllDigitAtBeginning(str);
 
// This code is contributed by rdtank
 
</script>


Output: 

123neveropen

 

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 = "neveropen1234";
    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
            = "neveropen1234";
        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 = "neveropen1234"
    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
            = "neveropen1234";
        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 = "neveropen1234";
moveAllDigitAtBeginning(str);
// contributed by akashish__


Output: 

1234neveropen

 

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments