Open In App

Move all special char to the end of the String

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to move all special char to the end of the String.

Examples: 

Input : !@$%^&*AJAY 
Output :AJAY!@$%^&*

Input :Geeksf!@orgeek@s A#$ c%o^mputer s****cience p#o@rtal fo@r ge%eks 
Output :Geeksforgeeks A computer science portal for geeks!@@#$%^****#@@%

Prerequisite: Regular Expressions in Java

The idea is to traverse the input string and maintain two strings, one string that contains normal characters (a, A, 1, ‘ ‘, etc) and another string that maintains special characters (@, $, etc). Finally, concatenate the two strings and return.

Implementation:

C++




// C++ program move all special char to the end of the string
 
#include <bits/stdc++.h>
using namespace std;
 
// Function return a string with all special
// chars to the end
string moveAllSC(string str)
{
    // Take length of string
    int len = str.length();
 
    // traverse string
    string res1 = "", res2 = "";
    for (int i = 0; i < len; i++)
    {
        char c = str.at(i);
 
        // check char at index i is a special char
        if (isalnum(c) || c == ' ')
            res1 += c;
        else
            res2 += c;
    }
 
    return res1 + res2;
}
 
// Driver code
int main()
{
    string str1("Geeksf!@orgeek@s A#$ c%o^mputer");
    string str2(" s****cience p#o@rtal fo@r ge%eks");
    string str = str1 + str2;
    cout << moveAllSC(str) << endl;
    return 0;
}
 
// This code is contributed by
// sanjeev2552


Java




// Java program move all special char to the end of the string
class GFG1 {
 
    // Function return a string with all special
    // chars to the end
    static String moveAllSC(String str)
    {
        // Take length of string
        int len = str.length();
 
        // regular expression for check char is special
        // or not.
        String regx = "[a-zA-Z0-9\\s+]";
 
        // traverse string
        String res1 = "", res2 = "";
        for (int i = 0; i < len; i++) {
         
            char c = str.charAt(i);
 
            // check char at index i is a special char
            if (String.valueOf(c).matches(regx))
               res1 = res1 + c;
            else
               res2 = res2 + c;
        }
        return res1 + res2;
    }
 
    public static void main(String args[])
    {
        String str = "Geeksf!@orgeek@s A#$ c%o^mputer"
                     + " s****cience p#o@rtal fo@r ge%eks";
        System.out.println(moveAllSC(str));
    }
}


Python3




# Python3 program move all special char
# to the end of the string
 
# Function return a string with all
# special chars to the end
def moveAllSC(string):
     
    # Take length of string
    length = len(string)
 
    # Traverse string
    res1, res2 = "", ""
    for i in range(0, length):
         
        c = string[i]
 
        # check char at index i is a special char
        if c.isalnum() or c == " ":
            res1 = res1 + c
        else:
            res2 = res2 + c
         
    return res1 + res2
     
# Driver Code
if __name__ == "__main__":
     
    string = "Geeksf!@orgeek@s A#$ c%o^mputer" \
            +" s****cience p#o@rtal fo@r ge%eks"
     
    print(moveAllSC(string))
     
# This code is contributed by Rituraj Jain


C#




// C# program move all special char
// to the end of the string
using System;
using System.Text.RegularExpressions;
 
class GFG
{
 
    // Function return a string with all
    // special chars to the end
    static String moveAllSC(String str)
    {
        // Take length of string
        int len = str.Length;
 
        // regular expression to check
        // char is special or not.
        var regx = new Regex("[a-zA-Z0-9\\s+]");
 
        // traverse string
        String res1 = "", res2 = "";
        for (int i = 0; i < len; i++)
        {
            char c = str[i];
 
            // check char at index i is a special char
            if (regx.IsMatch(c.ToString()))
                res1 = res1 + c;
            else
                res2 = res2 + c;
        }
        return res1 + res2;
    }
 
    public static void Main(String []args)
    {
        String str = "Geeksf!@orgeek@s A#$ c%o^mputer" +
                     " s****cience p#o@rtal fo@r ge%eks";
        Console.WriteLine(moveAllSC(str));
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
      // JavaScript program move all special char
      // to the end of the string
      // Function return a string with all
      // special chars to the end
      function moveAllSC(str) {
        // Take length of string
        var len = str.length;
 
        // regular expression to check
        // char is special or not.
        var regx = new RegExp("[a-zA-Z0-9\\s+]");
 
        // traverse string
        var res1 = "",
          res2 = "";
        for (var i = 0; i < len; i++) {
          var c = str[i].toString();
          // check char at index i is a special char
          if (regx.test(c)) res1 = res1 + c;
          else res2 = res2 + c;
        }
        return res1 + res2;
      }
 
      var str =
        "Geeksf!@orgeek@s A#$ c%o^mputer" + " s****cience p#o@rtal fo@r ge%eks";
      document.write(moveAllSC(str));
    </script>


Output

Geeksforgeeks A computer science portal for geeks!@@#$%^****#@@%















Complexity Analysis:

  • Time Complexity: O(N), as we use a loop to traverse N times. Where N is the length of the string.
  • Auxiliary Space: O(N), as we use extra space for the strings res1 and res2. Where N is the length of the string.

Approach 2:  Using two-pointers

  1. One pointer will start from the beginning of the string and the other pointer will start from the end of the string.
  2. The first pointer will move forward until it encounters a special character, while the second pointer will move backward until it encounters a non-special character. 
  3. Then, the two characters at the two pointers will be swapped.
  4. This process will continue until the two pointers meet in the middle.

Implementation:

C++




// C++ program for the above approach
#include <iostream>
using namespace std;
 
// Function to move all special characters
// to the end of the string
string moveSpecialCharToEnd(string s)
{
    string result = "";
    string specialChar = "";
 
    for (int i = 0; i < s.length(); i++) {
        if ((s[i] >= 'A' && s[i] <= 'Z')
            || (s[i] >= 'a' && s[i] <= 'z')
            || (s[i] >= '0' && s[i] <= '9')
            || s[i] == ' ') {
            result += s[i];
        }
        else {
            specialChar += s[i];
        }
    }
 
    return result + specialChar;
}
 
// Driver code
int main()
{
    string str = "Geeksf!@orgeek@s A#$ c%o^mputer "
                 "s****cience p#o@rtal fo@r ge%eks";
    cout << moveSpecialCharToEnd(str) << endl;
    return 0;
}


Java




public class Main {
    public static String moveSpecialCharToEnd(String s)
    {
        // Initialize an empty string to store alphanumeric
        // characters and spaces
        String result = "";
        // Initialize an empty string to store special
        // characters
 
        String specialChar = "";
        // Loop through each character in the input string
        // 's'
        for (int i = 0; i < s.length(); i++) {
            // Check if the current character is an
            // alphanumeric character (A-Z, a-z, 0-9) or a
            // space
            if ((s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')
                || (s.charAt(i) >= 'a'
                    && s.charAt(i) <= 'z')
                || (s.charAt(i) >= '0'
                    && s.charAt(i) <= '9')
                || s.charAt(i) == ' ') {
                // If it is alphanumeric or a space, add it
                // to the 'result' string
                result += s.charAt(i);
            }
            else {
                // If it is a special character, add it to
                // the 'specialChar' string
                specialChar += s.charAt(i);
            }
        }
        // Concatenate the 'result' string and 'specialChar'
        // string and return the final string
        return result + specialChar;
    }
 
    public static void main(String[] args)
    {
        // Input string containing alphanumeric and special
        // characters
        String str = "Geeksf!@orgeek@s A#$ c%o^mputer "
                     + "s****cience p#o@rtal fo@r ge%eks";
        // Call the moveSpecialCharToEnd method and print
        // the result
        System.out.println(moveSpecialCharToEnd(str));
    }
}


Python3




# Function to move all special characters
# to the end of the string
def moveSpecialCharToEnd(s):
    result = ""
    specialChar = ""
 
    for i in range(len(s)):
        # Check if the character is an alphabet or a digit
        if ((s[i] >= 'A' and s[i] <= 'Z')
            or (s[i] >= 'a' and s[i] <= 'z')
            or (s[i] >= '0' and s[i] <= '9')
                or s[i] == ' '):
            result += s[i]
        else:
            specialChar += s[i]
 
    return result + specialChar
 
# Driver code
str = "Geeksf!@orgeek@s A#$ c%o^mputer " \
      "s****cience p#o@rtal fo@r ge%eks"
print(moveSpecialCharToEnd(str))


C#




using System;
 
public class GFG
{
    // Function to move all special characters
    // to the end of the string
    public static string MoveSpecialCharToEnd(string s)
    {
        // Initialize two empty strings to store characters
        // based on whether they are special characters or not.
        string result = ""; // Stores non-special characters
        string specialChar = ""; // Stores special characters
 
        // Loop through each character in the input string 's'
        for (int i = 0; i < s.Length; i++)
        {
            // Check if the current character is an alphabet (uppercase or lowercase),
            // a digit, or a space. If yes, it is not a special character.
            if ((s[i] >= 'A' && s[i] <= 'Z')
                || (s[i] >= 'a' && s[i] <= 'z')
                || (s[i] >= '0' && s[i] <= '9')
                || s[i] == ' ')
            {
                // Append the non-special character to the 'result' string
                result += s[i];
            }
            else
            {
                // If the character is a special character, append it to the 'specialChar' string
                specialChar += s[i];
            }
        }
 
        // Concatenate the 'result' (non-special characters) and 'specialChar' (special characters) strings
        // and return the final string with special characters moved to the end.
        return result + specialChar;
    }
 
    // Driver code
    public static void Main()
    {
        // Input string with special characters
        string str = "Geeksf!@orgeek@s A#$ c%o^mputer "
                     + "s****cience p#o@rtal fo@r ge%eks";
 
        // Call the MoveSpecialCharToEnd function and print the result
        Console.WriteLine(MoveSpecialCharToEnd(str));
    }
}


Javascript




// Function to move special characters to the end of a string
function moveSpecialCharToEnd(s) {
    // Initialize variables to store the result and special characters
    let result = "";
    let specialChar = "";
 
    // Iterate through each character in the input string
    for (let i = 0; i < s.length; i++) {
        // Check if the character is an alphabet (uppercase or lowercase),
        // a digit, or a space
        if (
            (s[i] >= 'A' && s[i] <= 'Z') ||
            (s[i] >= 'a' && s[i] <= 'z') ||
            (s[i] >= '0' && s[i] <= '9') ||
            s[i] === ' '
        ) {
            // Append the character to the result if it's not a special character
            result += s[i];
        } else {
            // Otherwise, append the character to the specialChar variable
            specialChar += s[i];
        }
    }
 
    // Combine the result (alphabets, digits, and spaces) with the special characters
    return result + specialChar;
}
 
// Driver code
function main() {
    // Input string with special characters
    const str =
        "Geeksf!@orgeek@s A#$ c%o^mputer " +
        "s****cience p#o@rtal fo@r ge%eks";
     
    // Call the function to move special characters to the end
    const result = moveSpecialCharToEnd(str);
 
    // Display the modified string
    console.log(result);
}
 
// Call the main function to execute the program
main();


Output

Geeksforgeeks A computer science portal for geeks!@@#$%^****#@@%















Time Complexity: O(n), where n is the length of the input string, as the code is traversing the string only once.
Auxiliary Space: O(n), as two new strings are created to store the characters: one for normal characters and another for special characters. 

Approach 3 –  Using ‘isalnum()’ :

  1. Start with an empty string ‘special_chars’ to store the special characters and an empty string ‘normal_chars’ to store the normal characters.
  2. Iterate through each character ‘char’ in the input string.
  3. For each character:                                                                                                                                                                                         a. Check if char is alphanumeric or a space using the isalnum() method or if it is a whitespace character using the isspace() method.                                                                                                                                                                                      b. If char is alphanumeric or a space, append it to the normal_chars string.                                                                          c. If char is a special character, append it to the special_chars string.
  4. After iterating through all characters, return the concatenation of normal_chars and special_chars.
  5. End of the function.

Bellow is the implementation of the approach . 

C++




#include <iostream>
#include <string>
 
std::string moveAllSpecialChars(const std::string& input)
{
    std::string specialChars = "";
    std::string normalChars = "";
 
    // Separate special characters and normal characters
    for (char character : input) {
        if (isalnum(character) || isspace(character)) {
            normalChars += character;
        }
        else {
            specialChars += character;
        }
    }
 
    // Concatenate normal characters and special characters
    return normalChars + specialChars;
}
 
int main()
{
    std::string input = "Geeksf!@orgeek@s A#$ c%o^mputer "
                        "s****cience p#o@rtal fo@r ge%eks";
    std::string result = moveAllSpecialChars(input);
 
    // Print the result
    std::cout << result << std::endl;
 
    return 0;
}


Java




public class Main {
    // Function to move all special characters to the end of
    // the string
    public static String moveAllSpecialChars(String input)
    {
        String specialChars = "";
        String normalChars = "";
 
        // Separate special characters and normal characters
        for (char character : input.toCharArray()) {
            if (Character.isLetterOrDigit(character)
                || Character.isWhitespace(character)) {
                normalChars += character;
            }
            else {
                specialChars += character;
            }
        }
 
        // Concatenate normal characters and special
        // characters
        return normalChars + specialChars;
    }
 
    public static void main(String[] args)
    {
        String input = "Geeksf!@orgeek@s A#$ c%o^mputer "
                       + "s****cience p#o@rtal fo@r ge%eks";
        String result = moveAllSpecialChars(input);
 
        // Print the result
        System.out.println(result);
    }
}


Python




def move_all_special_chars(string):
    special_chars = ''
    normal_chars = ''
     
    for char in string:
        if char.isalnum() or char.isspace():
            normal_chars += char
        else:
            special_chars += char
     
    return normal_chars + special_chars
 
# Example usage
string = "Geeksf!@orgeek@s A#$ c%o^mputer s****cience p#o@rtal fo@r ge%eks"
result = move_all_special_chars(string)
print(result)


C#




using System;
using System.Text;
 
class Program {
    static string MoveAllSpecialChars(string input)
    {
        string specialChars = "";
        string normalChars = "";
 
        // Separate special characters and normal characters
        foreach(char character in input)
        {
            if (char.IsLetterOrDigit(character)
                || char.IsWhiteSpace(character)) {
                normalChars += character;
            }
            else {
                specialChars += character;
            }
        }
 
        // Concatenate normal characters and special
        // characters
        return normalChars + specialChars;
    }
 
    static void Main()
    {
        string input = "Geeksf!@orgeek@s A#$ c%o^mputer "
                       + "s****cience p#o@rtal fo@r ge%eks";
        string result = MoveAllSpecialChars(input);
 
        // Print the result
        Console.WriteLine(result);
 
        // Output: "Geeksforgeeks A computer science portal
        // for geeks!@#$%^****#@@@"
    }
}


Javascript




function moveAllSpecialChars(input) {
    let specialChars = "";
    let normalChars = "";
 
    // Separate special characters and normal characters
    for (let character of input) {
        if (/[a-zA-Z0-9\s]/.test(character)) {
            normalChars += character;
        } else {
            specialChars += character;
        }
    }
 
    // Concatenate normal characters and special characters
    return normalChars + specialChars;
}
 
// Example usage
let input = "Geeksf!@orgeek@s A#$ c%o^mputer s****cience p#o@rtal fo@r ge%eks";
let result = moveAllSpecialChars(input);
 
// Print the result
console.log(result);


Output

Geeksforgeeks A computer science portal for geeks!@@#$%^****#@@%















Time Complexity: O(n)
Auxiliary Space: O(n)



Last Updated : 27 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads