sha1
sha1

Reputation: 29

How can I identify special characters in a string? C#

I'm trying to get all characters in a string that occur before a certain character.

For example:

string id = "Hello everyone! Good day today.";
id = id.Remove(id.IndexOf('!'));
Console.WriteLine(id);
//output will be "Hello everyone"

And this works, but when I'm reading text from a special file and working with strings that contain special characters, I run into some trouble.

For example:

string id = "Hello everybodyø1Ø9ß&ëÄ"

If I wanted to only get the "Hello everybody" text, how would I do that? These special characters can be anything.

Upvotes: 0

Views: 4944

Answers (6)

satheesh
satheesh

Reputation: 71

We can make use of Regex under System.Text.RegularExpression. This reference should be added to the program file. This code helps to check whether the string contains a special character or not, new Regex(“[^A-Za-z0-9]”) and this helps to check whether the string consists of special charaters or not. There is a function called IsMatch() which return true when the string consists of special characters.

        string temp = "sathee *d@@lkr:d";
        Regex rgx = new Regex("[^A-Za-z0-9]");
        bool hasSpecialChars = rgx.IsMatch(temp);

Upvotes: 0

user14169749
user14169749

Reputation:

You can add Regex namespace. It allows replacing a special character with your desired character/number/symbol.

static void Main(string[] args)
    {
        string id = "Hello everybodyø1Ø9ß&ëÄ";
        string op = string.Empty;
        Console.WriteLine("i/p is " + id );
        Regex rgx = new Regex("[^A-Za-z0-9]");
        for (int i = 0; i < id.Length; i++)
        {
           bool isNUmber = int.TryParse(id[i].ToString(), out int n);
           op += (rgx.IsMatch(id[i].ToString()) || isNUmber  ) ? " " : id[i].ToString();
        }
        Console.WriteLine("O/p is " + op);
        Console.ReadLine();
    }

for more information : https://techstrology.com/c-sharp-if-string-contains-space-or-special-character/

Upvotes: 0

sha1
sha1

Reputation: 29

I looked into it and found my own solution that works like a charm

id = id.Remove(id.IndexOf(id.Where(x => !char.IsLetterOrDigit(x)).First()));

Upvotes: 0

Ran Turner
Ran Turner

Reputation: 18146

You could create an extension method added to string and use it as you wish.

Also note that I used StringBuilder since it doesn't create a new object in the memory but dynamically expands memory to accommodate the modified string (in contrast of doing it via regular string concatenation which could effect performance on long strings)

public static string GetRegularString(this string str) {
   StringBuilder sb = new StringBuilder();
   foreach (char c in str) {
      if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_' || c == ' ') {
         sb.Append(c);
      }
      else{
        break;
      }
   }
   return sb.ToString();
}

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460288

A simple way would be to specify the allowed chars and use Enumerable.TakeWhile:

string id = "Hello everybodyø1Ø9ß&ëÄ";
string allowedChars = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string result = string.Concat(id.TakeWhile(allowedChars.Contains)); // Hello everybody

Or use Regex as shown here(which just checks if there are special chars).

Upvotes: 2

user17154329
user17154329

Reputation:

Try this:

        string[] KeepCharacters = { "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," ", "~","`","!","@","#","$","%","^","&","*","(",")","-","_","+","=",@"\","|","}","]","{","[","'",":",";","/","?",".",">",",","<","1","2","3","4","5","6","7","8","9","0", Convert.ToString((char)34)};
        string id = "Hello everybodyø1Ø9ß&ëÄ";

        for(int i =0; i < id.Length; i++)
        {
            if(KeepCharacters.Contains(id.Substring(i,1).ToLower()) == false)
            {
                id = id.Remove(i);
                break;
            }
        }

Upvotes: 1

Related Questions