Remove all whitespace from C# string with regex

前端 未结 7 1581
遇见更好的自我
遇见更好的自我 2020-12-25 10:18

I am building a string of last names separated by hyphens. Sometimes a whitespace gets caught in there. I need to remove all whitespace from end result.

Sample strin

7条回答
  •  情歌与酒
    2020-12-25 10:53

    Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.

                           new string
                               (stringToRemoveWhiteSpaces
                                    .Where
                                    (
                                        c => !char.IsWhiteSpace(c)
                                    )
                                    .ToArray()
                               )
    

    OR

                           new string
                               (stringToReplaceWhiteSpacesWithSpace
                                    .Select
                                    (
                                        c => char.IsWhiteSpace(c) ? ' ' : c
                                    )
                                    .ToArray()
                               )
    

提交回复
热议问题