anon
anon

Reputation: 1

How do i strip special characters from the end of a string?

I need to strip unknown characters from the end of a string returned from an SQL database. I also need to log when a special character occurs in the string.

What's the best way to do this?

Upvotes: 0

Views: 845

Answers (5)

Kaveh Shahbazian
Kaveh Shahbazian

Reputation: 13513

Your definition of the problem is not precise yet this is a fast trick to do so:

string input;
...
var trimed = input.TrimEnd(new[] {'#','$',...} /* array of unwanted characters */);
if(trimed != input)
    myLogger.Log(input.Replace(trimed, ""));

Upvotes: 0

LukeH
LukeH

Reputation: 269288

Since you've specified that the legal characters are only alphanumeric, you could do something like this:

Match m = Regex.Match(original, "^([0-9A-Za-z]*)(.*)$");
string good = m.Groups[1].Value;
string bad = m.Groups[2].Value;

if (bad.Length > 0)
{
    // log bad characters
}

Console.WriteLine(good);

Upvotes: 0

Adam Fyles
Adam Fyles

Reputation: 6050

check out the Regex.Replace methods...there are lots of overloads. You can use the Match methods for the logging to identify all matches.

        String badString = "HELLO WORLD!!!!";

        Regex regex = new Regex("!{1,}$" );

        String newString = regex.Replace(badString, String.Empty);

Upvotes: -1

RvdK
RvdK

Reputation: 19790

First define what are unknown characters (chars other than 0-9, a to z and A to Z ?) and put them in an array Loop trough the characters of a string and check if the char occurs, if so remove. you can also to a String.Replace with as param the unknown char, and replaceparam ''.

Upvotes: 0

TLiebe
TLiebe

Reputation: 7966

You can use the Trim() method to trim blanks or specific characters from the end of a string. If you need to trim a certain number of characters you can use the Substring() method. You can use Regexs (System.Text.RegularExpressions namespace) to match patterns in a string and detect when they occur. See MSDN for more info.

If you need more help you'll need to provide a bit more info on what exactly you're trying to do.

Upvotes: 2

Related Questions