Remove leading and trailing spaces from a string in C#
This post will discuss how to remove leading and trailing spaces from a string in C#.
1. Using String.Trim() method
The standard solution to remove all whitespace characters from the beginning and end of the string is using the String.Trim() method. It returns a new string equal to the original string, but without leading and trailing spaces. Here’s an example of its usage.
|
1 2 3 4 5 6 7 8 9 10 11 |
using System; public class Example { public static void Main() { string s = " Trim Me "; Console.WriteLine($"\"{s.Trim()}\""); // "Trim Me" } } |
2. Using String.TrimStart() method
The String.Trim() method removes all whitespaces from the start and end of the input string. If you need to remove only leading whitespace characters from a string, use the String.TrimStart() method. It returns a string with all whitespace characters removed from the start of the input string. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 |
using System; public class Example { public static void Main() { string s = " Trim Me "; Console.WriteLine($"\"{s.TrimStart()}\""); // "Trim Me " } } |
3. Using String.TrimEnd() method
Alternatively, you can use the String.TrimEnd() method to remove only trailing whitespace characters from a string. It returns a string with all whitespace characters removed from the end of the input string.
|
1 2 3 4 5 6 7 8 9 10 11 |
using System; public class Example { public static void Main() { string s = " Trim Me "; Console.WriteLine($"\"{s.TrimEnd()}\""); // " Trim Me" } } |
Note that all the above methods do not modify the value of the original string object, and remove any leading/trailing characters for which the Char.IsWhiteSpace() method returns true.
That’s all about removing leading and trailing spaces from a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)