[Solved] C# Check the string contains special characters space or * / and how to replace them with some other value_ or %20 or some other characters.

There is a requirement where we are supposed to replace space * with an underscore. An example of a requirement is given below:

C# Check string has special characters or not

Input : rake *s@hr:d

Output: True

Check whether the string has special chars including number(s)

Input : rake *s@hr:d123

Output: True

C# How to replace the special characters(including numbers) with ‘_’

Input : rake *s@hr:d12

Output: rake__s_hr_d__

Write method to replace all space chars with %20

Input : rake s d

Output: rake%20s%20d

c# code to check if string contains special characters or not without using functions

Input : rake *s@hr:d

Output: true

c# code to check if string contains special characters or not and replace with underscore or %20(Including space)without using functions

Input : rake *s@hr:d

Output: rake%20s%20hr%20d

Solution:

Error: The type or namespace name ‘Regex’ could not be found (are you missing a using directive or an assembly reference?

If you found the error, Add reference by right-clicking on the Regex word or enter ctrl+. or click on the bulb symbol to add the reference.

There are different ways to solve this, By using Regex, This could be matched against the text input so that by using regular expression we can achieve all of the above things mentioned in the problem's section by using regular expression.

Approach 1: Code snippet is to check whether the string contains a special character(s) or not and, replace them with _ (underscore).

The below code snippet is to check whether the string contains a special character or not, new Regex(“[^A-Za-z0-9]”), the pattern is used to check whether the string contains special characters or not. IsMatch() the function checks the string and returns True then it replaces the special character with ‘_’.

using System;
using System.Text.RegularExpressions;
class Program
    {
        static void Main(string[] args)
        {
            string str = "rake *s@hr:d";
            string op = string.Empty;
            Console.WriteLine("i/p is " + str);
            Regex rgx = new Regex("[^A-Za-z0-9]");
            for (int i = 0; i < str.Length; i++)
            {
               op += (rgx.IsMatch(str[i].ToString())) ? "_" : str[i].ToString();
            }
            Console.WriteLine("O/p is " + op);
            Console.ReadLine();
        }
    }

Approach 2: Code snippet is to check whether the string contains a special character or not

The below code snippet is to check whether the string contains a special character or not. new Regex(“[^A-Za-z0-9]”) the pattern is used to check whether the string contains special characters or not. IsMatch() function checks the string and returns True if it contains a special character.

using System;
using System.Text.RegularExpressions;
class Program
    {
        static void Main(string[] args)
        {
            // Code to check string has special characters or not
            string str = "rake *s@hr:d";
            Console.WriteLine("I/P:-" + str);
            Regex rgx = new Regex("[^A-Za-z0-9]");
            bool hasSpecialChars = rgx.IsMatch(str);
            Console.WriteLine("Has string special character(s) : " + hasSpecialChars);
            Console.ReadLine();
        }
    }

Approach 3: Code snippet is to check whether the string contains a special character(including number ) or not

The below code snippet is to check whether the string contains a special character(including number ) or not. new Regex(“[^A-Za-z0-9]”) the pattern is used to check whether the string contains special characters or not. IsMatch() function checks the string and returns True if the string contains a special character. int.TryParse(str, out int n) the method returns True if the string contains the number(s).

using System;
using System.Text.RegularExpressions;
class Program
    {
        static void Main(string[] args)
        {
            // Check weather the string has special chars including number
            string str = "rake *s@hr:12d";
            Console.WriteLine("i/p is " + str);
            Regex rgx = new Regex("[^A-Za-z0-9]");
            bool isNUmber = int.TryParse(str, out int n);
            bool hasSpecialChars = rgx.IsMatch(str.ToString()) || isNUmber;
            Console.WriteLine("Has special chars: " + hasSpecialChars );
            Console.ReadLine();
        }
    }

Approach 4: Code snippet is to check check and replace special characters(including number(s))

The below code snippet is to check and replace special characters(including number(s)). new Regex(“[^A-Za-z0-9]”) the pattern is used to check whether the string contains special characters or not. IsMatch() function checks the string and returns True if the string contains a special character. int.TryParse(str, out int n) the method returns True if the string contains the number(s). Here either one of the conditions passes then the character will be replaced by ‘_’.

using System;
using System.Text.RegularExpressions;
class Program
    {
        static void Main(string[] args)
        {
            string str = "rake *s@hr:d";
            string op = string.Empty;
            Console.WriteLine("i/p is " + str);
            Regex rgx = new Regex("[^A-Za-z0-9]");
            for (int i = 0; i < str.Length; i++)
            {
               bool isNUmber = int.TryParse(str[i].ToString(), out int n);
               op += (rgx.IsMatch(str[i].ToString()) || isNUmber  ) ? "_" : str[i].ToString();
            }
            Console.WriteLine("O/p is " + op);
            Console.ReadLine();
        }
    }

Approach 5: Code snippet is to replace all space chars with %20 of a char array

Here the below code block replace all space chars with %20 and the method to accept char[] array and replaces the space to %20 and returns the char array result.

using System;
using System.Linq;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the Chars");
            char[] chars = Console.ReadLine().ToCharArray();
            chars = replaceSpaceWittPercent20(chars);
            Console.WriteLine(chars);
            Console.Read();
        }

        private static char[] replaceSpaceWittPercent20(char[] chars)
        {
            string m = string.Empty;
            string s = string.Empty;
            foreach (char c in chars)
            {
                m += c;
            }
            foreach (char n in m)
            {
                if (n == ' ')
                {
                    s += "%20";
                    continue;
                }
                s += n;
            }
            return s.ToCharArray();
        }
    }
}
Approach 6: Check if string contains special characters or not without using functions

The below code approach will check every character and is a special character and returns a boolean true or false.

using System;
class Program
{
    static void Main(string[] args)
    {
        string str = "`~@raked";
        bool flag = hasSpecialChar(str);
        if (flag)
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
        Console.ReadLine();
    }

    public static bool hasSpecialChar(string input)
    {
        string specialChar = @"|!#$%&/()=?»«@£§€{}.-;~`'<>_,1234567890";
        foreach (var item in specialChar)
        {
            if (input.Contains(item)) return true;
        }

        return false;
    }
}

Approach 7: check if the string contains special characters or not and replace with underscore or %20(Including space)without using functions

The below code approach will check every character and is a special character and replace it with %20including number or space and returns a new string.

using System;
class Program
{
    static void Main(string[] args)
    {
        string str = "`~@raked ";
        string replaceChar = "%20";
        string output = hasSpecialChar(str, replaceChar);
        Console.WriteLine(output);
    }

    public static string hasSpecialChar(string input, string chars)
    {
        string word = string.Empty;
        string specialChar = @"|!#$%&/()=?»«@£§€{}.-;~`'<>_,1234567890 ";
        foreach (var item in input)
        {
            if (specialChar.Contains(item))
            {
                word += chars;
            }
            else
            {
                word += item;
            }
        }
        return word;
    }
}

Conclusion

regular expression is a pattern that could be matched against an input text. By using the Regex pattern matching technique we achieved that string contains special characters or not, replaced the special character text with some other value (like ‘_’). I hope you find them helpful.

Default image
Shivaraju M
Over 3+ years experience in IT industry, good knowledge in . Net-based Web applications, windows applications, web services, and SPAs. I have played multiple roles related to technical delivery in multiple domains while working on over 10+ technologies. I am currently focused on continuous improvement and agile project management.

Leave a Reply