简体   繁体   English

删除c#中字符串中前导特殊字符的最快方法

[英]Fastest way to remove the leading special characters in string in c#

I am using c# and i have a string like 我正在使用c#,我有一个字符串

-Xyz
--Xyz
---Xyz
-Xyz-Abc
--Xyz-Abc

i simply want to remove any leading special character until alphabet comes , Note: Special characters in the middle of string will remain same . 我只想删除任何前导特殊字符,直到字母表出现, 注意:字符串中间的特殊字符将保持不变。 What is the fastest way to do this? 最快的方法是什么?

You could use string.TrimStart and pass in the characters you want to remove: 您可以使用string.TrimStart并传入要删除的字符:

var result = yourString.TrimStart('-', '_');

However, this is only a good idea if the number of special characters you want to remove is well-known and small. 但是,如果要删除的特殊字符数众所周知且很小,这只是一个好主意。
If that's not the case, you can use regular expressions: 如果不是这样,您可以使用正则表达式:

var result = Regex.Replace(yourString, "^[^A-Za-z0-9]*", "");

I prefer this two methods: 我更喜欢这两种方法:

List<string> strings = new List<string>()
{
    "-Xyz",
    "--Xyz",
    "---Xyz",
    "-Xyz-Abc",
    "--Xyz-Abc"
};

foreach (var s in strings)
{
    string temp;

    // String.Trim Method
    char[] charsToTrim = { '*', ' ', '\'', '-', '_' }; // Add more
    temp = s.TrimStart(charsToTrim);
    Console.WriteLine(temp);

    // Enumerable.SkipWhile Method
    // Char.IsPunctuation Method (se also Char.IsLetter, Char.IsLetterOrDigit, etc.)
    temp = new String(s.SkipWhile(x => Char.IsPunctuation(x)).ToArray());
    Console.WriteLine(temp);
}

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

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