TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Trim Strings

Use the Trim method. Trim removes characters on the start and end of strings.
Trim. This method eliminates leading and trailing whitespace. We need to remove whitespace from the beginning or ending of a string. We use the Trim method to do this efficiently.Strings
Other characters. But Trim() is not limited to just spaces. It removes any characters specified. Its behavior changes when we pass arguments to it.
Example. Here we remove spaces from the beginning and end of a string. When we call Trim on a string, it copies the string and returns a modified version as the copy.

Step 1: We specify an input string, which (like all strings) is immutable. The original is not changed when we call Trim.

Step 2: Trim() can be used with no parameters. In this case it uses a default set of whitespace characters.

Step 3: The Console.WriteLine statement prints the copied string that has no spaces at the beginning or end.

Console
C# program that uses Trim using System; class Program { static void Main() { // Step 1: input string. string value = " This is an example string. "; // Step 2: call Trim instance method. // ... This returns a new string copy. value = value.Trim(); // Step 3: write to screen. Console.WriteLine("TRIMMED: [{0}]", value); } } Output TRIMMED: [This is an example string.]
Line breaks. We can remove newlines from strings with Trim. The Trim method will remove both UNIX style line breaks and Windows style line breaks.

WriteLine: It uses two Console.WriteLine method calls, each of which format the string they display.

Output: This is surrounded by square brackets. Trim copies the input string, modifies the copy, and then returns a new copy.

C# program that uses Trim, removes newlines using System; class Program { static void Main() { // Input string. string st = "This is an example string.\r\n\r\n"; Console.WriteLine("[{0}]", st); st = st.Trim(); Console.WriteLine("[{0}]", st); } } Output [This is an example string. ] [This is an example string.]
Files. We next trim each line from a file. This works well with StreamReader or other File methods. The example here demonstrates Trim on each line in the file.

Note: The file, located at path "file.txt" contains three lines, each ending with a space.

First: The code first uses File.ReadAllLines. Then it loops through the lines using foreach.

File.ReadAllLines

Then: Each line is trimmed. Because all the lines are in memory, the original file is not changed.

C# program that uses Trim with file using System; using System.IO; class Program { static void Main() { foreach (string line in File.ReadAllLines("file.txt")) { Console.WriteLine("[" + line + "]"); string trimmed = line.Trim(); Console.WriteLine("[" + trimmed + "]"); } // In the loop you can use both strings. // ... No string is actually changed. // ... Trim copies the string. } } Output [This file ] [This file] [Has some ] [Has some] [Whitespace you don't want ] [Whitespace you don't want]
TrimStart, TrimEnd. A separate article shows the TrimStart method. Please consult the article for a detailed discussion of TrimStart and its usage patterns.TrimEnd, TrimStart

Also: It is useful to call TrimEnd to remove punctuation from the ends of strings, such as the ending punctuation in a sentence.

Implementation. Looking in IL Disassembler at the MSIL code, Trim calls an internal method called TrimHelper. This contains several loops, and uses an O(N squared) algorithm.IL Disassembler

Warning: This means Trim() loops within loops. Finally it calls InternalSubString.

Tip: If you have to Trim many different chars, it would be faster to use a lookup table to test if the character is to be removed.

Therefore: Implementing a custom Trim that uses an array lookup instead of a nested loop would be faster. This was not benchmarked here.

Performance. I tested how Trim performs on different strings. For example, I benchmarked Trim on a string that has characters to be trimmed, against a string that doesn't need changing.

And: My results were that Trim takes more time when it has more characters to remove from the source string.

Note: Trim() iterates through the characters until no more trimming can be done. No numbers are available in this document.

Methods. There are other ways you will need to change or replace the whitespace in strings. For example, you may need to change whitespace in the middle of strings, not just on the end.Whitespace
Punctuation is another common character type we need to trim. This can be challenging with just the Trim method—a custom array is required.Remove Punctuation
Regex. There are other ways to Trim strings, such as with regular expressions. These approaches are documented elsewhere on this site. They tend to be more complex.Regex TrimRegex
A summary. We saw many examples and tips for the Trim method. We found potential problems with Trim. And we pointed to various alternatives.
As a developer, I have used Trim in every nontrivial program I have written. Trim() is useful. It is easy to remember and reliable.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf