How to trim whitespace between characters

后端 未结 9 1882
天命终不由人
天命终不由人 2020-12-05 07:17

How to remove whitespaces between characters in c#?

Trim() can be used to remove the empty spaces at the beginning of the string as well as at the end.

9条回答
  •  余生分开走
    2020-12-05 08:08

    I found this method great for doing things like building a class that utilizes a calculated property to take lets say a "productName" and stripping the whitespace out to create a URL that will equal an image that uses the productname with no spaces. For instance:

        namespace XXX.Models
        {
            public class Product
            {
                public int ProductID { get; set; }
                public string ProductName { get; set; }
                public string ProductDescription { get; set; }
    
                public string ProductImage
                {
                    get { return ProductName.Replace(" ", string.Empty) + ".jpg"; }
                }
            }
        }
    

    So in this answer I have used a very similar method as w69rdy, but used it in an example, plus I used string.Empty instead of "". And although after .Net 2.0 there is no difference, I find it much easier to read and understand for others who might need to read my code. I also prefer this because I sometimes get lost in all the quotes I might have in a code block.

提交回复
热议问题