2017-07-25 29 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你是對的,我已經更新了。 –

相關問題