Louis Tran
Louis Tran

Reputation: 1156

How to keep only numbers and some special characters in a string?

I have a string containing regular characters, special characters and numbers. I'm trying to remove the regular characters, just keeping the numbers and the special characters. I use a loop to check if a character is a special character or a number. Then, I replace it with an empty string. However, this doesn't seem to work because I get an error "can't apply != to string or char". My code is below. If possible, please give me some ideas to fix this. Thanks.

public string convert_string_to_no(string val)
{
    string str_val = "";
    int val_len = val.Length;
    for (int i = 0; i < val_len; i++)
    {
        char myChar = Convert.ToChar(val.Substring(i, 1));
        if ((char.IsDigit(myChar) == false) && (myChar != "-"))
        {
             str_val = str_val.replace(str_val.substring(i,1),"");
        }
    }
    return str_val;
} 

Upvotes: 2

Views: 6087

Answers (3)

Erik Philips
Erik Philips

Reputation: 54618

I perfer Linq:

public static class StringExtensions
{
  public static string ToLimitedString(this string instance,
    string validCharacters)
  {
    // null reference checking...

    var result = new string(instance
      .Where(c => validCharacters.Contains(c))
      .ToArray());

    return result;
  }
}

usage:

var test ="Q1W2-hjkxas1-EE3R4-5T";
var limited = test.ToLimitedString("01234567890-");
Console.WriteLine(limited);

result:

12-1-34-5

DotNetFiddle Example

Upvotes: 2

Pavan Teja
Pavan Teja

Reputation: 3202

you can use regular expressions to do that.its faster than using loop and clean

    String test ="Q1W2-hjkxas1-EE3R4-5T";
    Regex rgx = new Regex("[^0-9-]");
    Console.WriteLine(rgx.Replace(test, ""));

check the working code here

Upvotes: 5

Hazem Torab
Hazem Torab

Reputation: 379

It seem try to change "-" to '-', and better to construct the string and not replacing the char.

public string convert_string_to_no(string val)
    {
        string str_val = "";
        int val_len = val.Length;
        for (int i = 0; i < val_len; i++)
        {
            char myChar = Convert.ToChar(val.Substring(i, 1));
            if (char.IsDigit(myChar) && myChar == '-')
            {
                 str_val +=  myChar; 
            }
        }
        return str_val;
    } 

Upvotes: 3

Related Questions