[Piggy-backing - followups set to comp.lang.c]
Keith Thompson said:
Kevin Smith <no@spam.comwrites:
>According to the intellisense help, string.Trim() "Removes all
occurances or white space characters from the beginning and end of this
instance."
[snip]
You posted this to microsoft.public.dotnet.languages.csharp, where I
presume it's topical. Why on Earth did you redirect followups to
comp.lang.c?
Anyone else replying to Kevin Smith's article, please *ignore* the
Followup-To header and post only to the csharp group. Thanks.
Sorry, Keith, but my reply is C-relevant as well as C#-relevant.
(Incidentally, I'm piggybacking because my newsreader didn't see the
article in the normal feed, but I'm able to comment on the article because
my newsreader *could* find the article on an ID search - go figure,
because I can't.)
The question is:
"the follow code does not appear to modify s.
s.Trim('\r');
While the follow code DOES modify s.
s = s.Trim(\r');
If this is modifying this instance, why do I only get the effect if I
assign the result?"
And the answer is simple to deduce, but quite difficult to frame in a way
that is relevant in both cross-posted groups. Nevertheless, I intend to
try.
Operations take inputs and produce results. Very often, those operations do
not modify their inputs - and this is a Good Thing. If the subtraction
operator modified its input, we'd be furious: x = 6 - 2; would change 6
into 4, so printf("%d\n", 6) would produce 4 from now on!
Your code: s.Trim('\r'); is roughly analogous to x - 2. That is, if you
were to write this:
x - 2;
you would expect the code to do nothing. (You might even expect it to
result in a compilation error but, if so, you would be disappointed.)
But if you were to write this:
x = x - 2;
you would have every right to expect that x's value would be updated.
Now, C isn't C#, but it's not beyond the wit of mankind to imagine a C
variant in which strings are genuine first-class objects rather than mere
arrays of char. In such a language, one might reasonably implement a trim
function in a manner such as this:
string trim(string in)
{
string out = "";
size_t i = 0;
size_t j = in.length;
while(i < in.length && isspace(in.str[i]))
{
++i;
}
while(j 0 && isspace(in.str[j - 1]))
{
--j;
}
while(i < j)
{
out.append(in.str[i++]);
}
return out;
}
(Okay, so this isn't exactly legal C, but it wouldn't take much to make it
so.) The point is that this function accepts an input which it does not
modify - it creates a new object whose value it returns on completion. And
that's what your C# Trim function is doing, and that's why you have to say
s = s.Trim('\r').
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999