Search code examples
c#trim

Creating a char array for TrimEnd and TrimStart


I have to remove leading and trailing numeric characters from a string in our web-service client project as for some reason the web-service at the other end in Norway won't accept Nicosia 1121 as a string...

So I decided to build a little re-useable function that would do it:

public static string CleanNosFromStr(string text, char charsToRemove)
{ 
    var CleanedStr = text.TrimEnd(charsToRemove).TrimStart(charsToRemove);
        return CleanedStr.ToString();
    } 

and I wanted to call it like this:

char chars2Remove= new string("0,1,2,3,4, 5,6,7,8,9,0, ").Split(",");

wsSoapBody.CardCity = 
myextensions.CleanNosFromStr(aMessage[(int)cardCreate.CardCity].ToString(),chars2Remove);    

But it won't compile...

The compilation errors I am getting are:

The best overloaded method match for 'string.String(char*)' has some invalid arguments

Argument 1: cannot convert from 'string' to 'char*'

Where am I going wrong, and is there a better way?

Of course I could just use

wsSoapBody.CardCity = aMessage[(int)cardCreate.CardCity].ToString().TrimEnd
('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ' ').
TrimStart('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ' ');

but I'd prefer to have something re-useable.

Thanks


Solution

  • Some points:

    1. text.TrimEnd(charsToRemove).TrimStart(charsToRemove) can be shortened with text.Trim(charsToRemove).
    2. Trim, TrimStart and TrimEnd accepts single or multiple chars (see String.Trim).
    3. Your code new string("0,1,2,3,4, 5,6,7,8,9,0, ").Split(",") should be "0,1,2,3,4,5,6,7,8,9, ".Split(',')...
    4. But it could be better expressed with "0123456789 ".ToCharArray().

    Finally your code could be:

    private static readonly char[] NosCharsToRemove = "0123456789 ".ToCharArray();
    public static string CleanNosFromStr(string text)
    { 
        return text.Trim(NosCharsToRemove);
    }
    

    and

    wsSoapBody.CardCity = myextensions.CleanNosFromStr(aMessage[(int)cardCreate.CardCity].ToString());