2017-07-25 28 views
0

如何过滤输入字符串中的特定字符? 请参阅下面的我已经尝试过。如何过滤掉用户在c#中输入字符的字符?

using System; 

    namespace PlainTest 
    { 
     class arrayTest 
     { 
      static void Main(string[] args) 
      { 
       bool doAlways = true; 
       int i = 1; 
       do 
       { 
        Console.WriteLine("Test Number : {0}", i++); 
        Console.Write("Key in the string: "); 
        char[] alpha = { 'a', 'b', 'c' }; 
        string text = Console.ReadLine(); 
        string filterAlphabet = text.Trim(alpha); 
        Console.WriteLine("The input is : {0}", text); 
        Console.WriteLine("Ater trimed the alpha a,b,c : {0}", filterAlphabet); 


       } while (doAlways == true); 
      } 
     } 
    } 

但是,当我试图与字符之间的数字修剪。该过滤器不起作用。请参阅下面的输出不同的输入。

Test Number : 1 
Key in the string: 123abc 
The input is : 123abc 
Ater trimed the alpha a,b,c : 123 

Test Number : 2 
Key in the string: abc123 
The input is : abc123 
Ater trimed the alpha a,b,c : 123 

**Test Number : 3 
Key in the string: aa1bb2cc3 
The input is : aa1bb2cc3 
Ater trimed the alpha a,b,c : 1bb2cc3** 

Test Number : 4 
Key in the string: aaabbbccc123 
The input is : aaabbbccc123 
Ater trimed the alpha a,b,c : 123 

Test Number : 5 
Key in the string: a12bc 
The input is : a12bc 
Ater trimed the alpha a,b,c : 12 

Test Number : 6 
Key in the string: 

请告诉我。 谢谢。

+2

你看了[文件](https://msdn.microsoft.com/en-us/ library/d4tt83f9(v = vs.110).aspx)为'String.Trim'? *从当前String对象中删除数组中指定的一组字符的前导和尾随**。粗略的Google搜索将显示此文档以及有关此问题的其他参考。在问你的下一个问题之前,请做更多的研究工作。 [Stack Overflow用户需要多少研究工作?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – tnw

回答

2

而不是使用trim,你可以遍历字符串来寻找您要删除,并用一个空字符串替换它们的字符:

var alpha = new string[] { "a", "b", "c" }; 
foreach (var c in alpha) 
{ 
    text = text.Replace(c, string.Empty); 
} 
0

TRIM(的char [])只删除开头或结尾字符,就像Trim()去除前导/尾随白色空间一样。只要Trim击中一个不在数组中的字符,它就会停止(从前面和后面一起工作)。为了摆脱任何地方你想要的角色,你需要使用替换或正则表达式。

0

你可以使用正则表达式。

而不是

string filterAlphabet = text.Trim(alpha); 

使用正则表达式来代替A,B,C

string filterAlphabet = Regex.Replace(text,"[abc]",string.Empty); 
+1

@ DaveBecker你是对的,我已经更新了。 –

相关问题