Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to trim whitespace and other characters from a string?

For example, if I want to remove whitespace and trailing commas from a string, I can do this:

String x = "abc,\n";
x.Trim().Trim(new char[] { ',' });

which outputs abc correctly. I could easily wrap this in an extension method, but I'm wondering if there is an in-built way of doing this with a single call to Trim() that I'm missing. I'm used to Python, where I could do this:

import string
x = "abc,\n"

x.strip(string.whitespace + ",")

The documentation states that all Unicode whitespace characters, with a few exceptions, are stripped (see Notes to Callers section), but I'm wondering if there is a way to do this without manually defining a character array in an extension method.

Is there an in-built way to do this? The number of non-whitespace characters I want to strip may vary and won't necessarily include commas, and I want to remove all whitespace, not just \n.

like image 338
Ricardo Altamirano Avatar asked Dec 26 '22 20:12

Ricardo Altamirano


1 Answers

Yes, you can do this:

x.Trim(new char[] { '\n', '\t', ' ', ',' });

Because newline is technically a character, you can add it to the array and avoid two calls to Trim.

EDIT

.NET 4.0 uses this method to determine if a character is considered whitespace. Earlier versions maintain an internal list of whitespace characters (Source).

If you really want to only use one Trim call, then your application could do the following:

  1. On startup, scan the range of Unicode whitespace characters, calling Char.IsWhiteSpace on each character.
  2. If the method call returns true, then push the character onto an array.
  3. Add your custom characters to the array as well

Now you can use a single Trim call, by passing the array you constructed.

I'm guessing that Char.IsWhiteSpace depends on the current locale, so you'll have to pay careful attention to locale.

like image 50
Chris Laplante Avatar answered Apr 30 '23 08:04

Chris Laplante