简体   繁体   中英

A Linq to replace unwanted characters

I have a Linq code to get acceptable characters and remove others. But this code replace others with ""(nothing + null+ string.empty etc) I would like to replace with space ( ). How can I do it?

Thanks a lot.

string clean = new string(incomingText.Where(c => @" 0123456789abcçdefgğhıijklmnöopqrsştuüvwxyz".Contains(c)).ToArray());

Well you could use:

// Alternatively use a HashSet<char>
string acceptableCharacters = " 1234...";
string clean = new string(incomingText.Select(c => acceptableCharacters.Contains(c) ?
                                                   c : ' ')
                                      .ToArray());

Note that this still really isn't terribly efficient. I'd probably use a call to Regex.Replace instead.

Regex invalidCharacterPattern = new Regex("[^ 0-9a-zçğıöşü]");
string clean = invalidCharacterPattern.Replace(incomingText, " ");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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