C # 3.0 Remove characters from string

I have a line and what

  • delete all characters except all English letters (a..z)
  • replace all spaces with one string

How would you do this with C # 3.0?

+3
source share
4 answers

Regex (edited)?

string s = "lsg  @~A\tSd 2£R3 ad"; // note tab
s = Regex.Replace(s, @"\s+", " ");
s = Regex.Replace(s, @"[^a-zA-Z ]", ""); // "lsg A Sd R ad"
+8
source

Of course, the Regex solution is the best (I think). But someone has to do this in LINQ, so I had fun. There you go:

bool inWhiteSpace = false;
string test = "lsg  @~A\tSd 2£R3 ad";
var chars = test.Where(c => ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || char.IsWhiteSpace(c))
                 .Select(c => {
                     c = char.IsWhiteSpace(c) ? inWhiteSpace ? char.MinValue : ' ' : c;
                     inWhiteSpace = c == ' ' || c == char.MinValue;
                     return c;
                 })
                 .Where(c => c != char.MinValue);
string result = new string(chars.ToArray());
+5
source

, !

string myCleanString = Regex.Replace(stringToCleanUp, @"[\W]", "");
string myCleanString = Regex.Replace(stringToCleanUp, @"[^a-zA-Z0-9]", "");
+2

Source: https://habr.com/ru/post/1716474/


All Articles