简体   繁体   English

如何从字符串末尾去除特殊字符?

[英]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. 我需要从SQL数据库返回的字符串的末尾去除未知字符。 I also need to log when a special character occurs in the string. 当字符串中出现特殊字符时,我还需要记录。

What's the best way to do this? 最好的方法是什么?

You can use the Trim() method to trim blanks or specific characters from the end of a string. 您可以使用Trim()方法来修剪字符串末尾的空白或特定字符。 If you need to trim a certain number of characters you can use the Substring() method. 如果需要修剪一定数量的字符,可以使用Substring()方法。 You can use Regexs (System.Text.RegularExpressions namespace) to match patterns in a string and detect when they occur. 您可以使用Regexs(System.Text.RegularExpressions命名空间)来匹配字符串中的模式并检测它们何时发生。 See MSDN for more info. 有关更多信息,请参见MSDN

If you need more help you'll need to provide a bit more info on what exactly you're trying to do. 如果您需要更多帮助,则需要提供更多有关您要尝试执行的操作的信息。

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. 首先定义什么是未知字符(0-9以外的字符,a到z和A到Z?),然后将它们放入数组中,通过字符串的字符循环,并检查是否出现了char,如果是,则将其删除。 you can also to a String.Replace with as param the unknown char, and replaceparam ''. 您还可以将String.Replace替换为未知char作为param并替换param''。

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, ""));

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);

check out the Regex .Replace methods...there are lots of overloads. 看看Regex .Replace方法...有很多重载。 You can use the Match methods for the logging to identify all matches. 您可以使用Match方法进行日志记录,以识别所有匹配项。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM