How to move all special characters to the beginning of a string in C#

2 Answers

0 votes
using System;
using System.Text.RegularExpressions;
 
class Program
{
    static String move_special_characters_to_beginning(String s) {
        int len = s.Length;
 
        var regx = new Regex("[a-zA-Z0-9]");
 
        String chars = "", pecial_characters = "";
        for (int i = 0; i < len; i++) { 
            char ch = s[i]; 
            if (regx.IsMatch(ch.ToString())) 
                chars = chars + ch; 
            else
                pecial_characters = pecial_characters + ch; 
        } 

        return pecial_characters + chars;
    } 
    static void Main() {
        String s = "c++$vb.net&%java*() php c# <>/python 3.7.3"; 
         
        Console.WriteLine(move_special_characters_to_beginning(s));
    }
}
 

 
/*
run:
 
++$.&%*()  # <>/ ..cvbnetjavaphpcpython373
 
*/

 



answered Aug 13, 2019 by avibootz
edited Dec 12, 2025 by avibootz
0 votes
using System;

class Program
{
    static string MoveSpecialCharactersToBeginning(string s) {
        string specials = "";
        string chars = "";

        foreach (char ch in s) {
            if (char.IsLetterOrDigit(ch) || char.IsWhiteSpace(ch)) {
                chars += ch;
            }
            else {
                specials += ch;
            }
        }

        return specials + chars;
    }

    static void Main()
    {
        string s = "c++20$c&^java*(rust) php <>/python 3.14.2";
        
        Console.WriteLine(MoveSpecialCharactersToBeginning(s));
    }
}



/*
run:

++$&^*()<>/..c20cjavarust php python 3142

*/


 



answered Dec 12, 2025 by avibootz

Related questions

...