Thread: string.Trim

  1. #1
    Registered User
    Join Date
    Jan 2007
    Posts
    330

    string.Trim

    strings are immutable classes, fine

    but consider the Trim function. What happens when Trim finds out theres nothing to trim. Will it do just "return this" or "return new string(this)"
    ??

  2. #2
    Registered User
    Join Date
    Jan 2007
    Posts
    330
    nvm, the following code prints true for s1 = "test" and false for "test "

    Code:
    string s1 = "test";
    string s2 = s1.Trim();
    
    Console.WriteLine(object.ReferenceEquals(s1, s2));

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You can always decompile the string.Trim() method to find out also:

    Code:
    public string Trim()
    {
    	return this.TrimHelper(2);
    }
    
    private string TrimHelper(int trimType)
    {
    	int num = this.Length - 1;
    	int num2 = 0;
    	if (trimType != 1)
    	{
    		num2 = 0;
    		while (num2 < this.Length && char.IsWhiteSpace(this[num2]))
    		{
    			num2++;
    		}
    	}
    	if (trimType != 0)
    	{
    		num = this.Length - 1;
    		while (num >= num2 && char.IsWhiteSpace(this[num]))
    		{
    			num--;
    		}
    	}
    	return this.CreateTrimmedString(num2, num);
    }
    
    private string CreateTrimmedString(int start, int end)
    {
    	int num = end - start + 1;
    	if (num == this.Length)
    	{
    		return this;
    	}
    	if (num == 0)
    	{
    		return string.Empty;
    	}
    	return this.InternalSubString(start, num, false);
    }
    You can see that if the length doesn't change it just returns itself.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 11-05-2012, 03:27 PM
  2. trim last character of a string
    By khoavo123 in forum C Programming
    Replies: 11
    Last Post: 02-28-2012, 01:56 AM
  3. Replies: 10
    Last Post: 12-04-2010, 12:04 AM
  4. Trim A String
    By pittuck in forum C++ Programming
    Replies: 5
    Last Post: 12-06-2003, 07:38 AM
  5. trim string function (code)
    By ipe in forum C Programming
    Replies: 9
    Last Post: 01-06-2003, 12:28 AM