Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string.Substring() as part of a chain

I'm trying to maniplulate a string without making a big issue out of it and spreading it out onto multiple lines, so I'm using some chaining to achieve this. The question I have is, how do I use string.Substring() to drop the last character off my string in this context?

In PHP I can pass a negative number as an argument (i.e. substr(-1)) to achieve this, but obviously this isn't how C# works.

mystring = mystring.Replace('_', ' ').Substring(???);

Also, what is the actual name for the technique used above? I always referred to it as a callback chain, but a callback chain I now think is something completely different.

Please note I want to avoid:

mystring = mystring.Replace('_', ' ');
mystring = mystring.Substring(0, mystring.Length - 1);

Thanks in advance for your time and kind consideration.

Iain

Thanks for your answers guys. It's funny that people can have such strong opinions about string manipulation and other "competing" languages :)

like image 669
Iain Fraser Avatar asked Nov 18 '09 07:11

Iain Fraser


3 Answers

You could write an Extension method RightStrip(). You can't overload SubString for negative start positions.

static string RightStrip(this string s, int n)
{
    return s.Substring(0, s.Length - n);
}


string s = "Hello World!";
s = s.Replace('e', 'a').RightStrip(1);
like image 123
Henk Holterman Avatar answered Sep 18 '22 17:09

Henk Holterman


Create an extension class like this:

public static class MyStringExtensions
{
    public static string RemoveCharactersFromEnd(this string s, int n)  
    {  
        string result = string.Empty;  

        if (string.IsNullOrEmpty(s) == false && n > 0)
        {
            result = s.Remove(s.Length - n, n);
        }

        return result;
    }
}  

Call it:

Console.WriteLine("test!!".RemoveCharactersFromEnd(2));

like image 29
Michel van Engelen Avatar answered Sep 18 '22 17:09

Michel van Engelen


In your sample, you are chaining to a method that doesn't change the length of the original string. Hence answers suggesting using SubString with (originalLength-1), which of course doesn't work in the general case.

The answer as you seem to have realized is - you can't do it in the general case, where previous methods in the chain have modified the length.

But you can write your own extension method in 3.5 to do what you want. Something like the following or a variant thereof:

public static string PhpSubstring(this string value, int length)
{
    if (length < 0) length = value.Length - length;
    return String.Substring(value, length);
}
like image 31
Joe Avatar answered Sep 17 '22 17:09

Joe