C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
ConsoleC# 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.]
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.]
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.ReadAllLinesThen: 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]
Also: It is useful to call TrimEnd to remove punctuation from the ends of strings, such as the ending punctuation in a sentence.
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.
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.