C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The string array "items" here is used to show the results of TrimEnd. The TrimEnd method itself receives chars, not strings.
ArrayCharFirst: The example first creates a string array. Each string in the array is looped over with the foreach-loop.
Then: TrimEnd is called. It removes the question mark, period and comma from the string.
C# program that uses TrimEnd
using System;
class Program
{
static void Main()
{
// Our example string array.
string[] items = new string[]
{
"Who's there?",
"I am here..."
};
// Loop and call TrimEnd.
foreach (string item in items)
{
string trimmed = item.TrimEnd('?', '.', ',');
Console.WriteLine(item);
Console.WriteLine(" " + trimmed);
}
Console.ReadLine();
}
}
Output
Who's there?
Who's there
I am here...
I am here
Tip: You don't need an array, although you can use an array. The method is versatile.
Signature of TrimEnd method: C#
string string.TrimEnd(params char[] trimChars)
Removes all trailing occurrences of a set of characters specified...
Note: You can send the method an entire array, or just several parameters separated by commas.
ParamsExample of TrimEnd with many parameters: C#
string t = s.TrimEnd('?', '.', ',');
Example of TrimEnd with array: C#
char[] c = new char[]
{
'?',
'.',
','
};
string t = s.TrimEnd(c);
Note: We must provide a parameter to TrimStart, which contains the characters you want to Trim.
Tip: The characters can be anything. We do not need to use whitespace characters.
C# program that uses TrimStart
using System;
class Program
{
static void Main()
{
string text = "\t, again and again."; // Trim this string.
char[] arr = new char[] { '\t', ',', ' ' }; // Trim these characters.
text = text.TrimStart(arr);
Console.WriteLine(text);
}
}
Output
"again and again."
Loop: In the loop, we count the number of characters to remove. And finally we return a substring using that value.
Note: This method removes trailing punctuation from a string. It performs more than twice as fast as the TrimEnd method.
Remove PunctuationAnd: This could be a useful trick if you have a lot of trimming to do in an important program.
Optimized trim implementation: C#
static string TrimTrailingChars(string value)
{
int removeLength = 0;
for (int i = value.Length - 1; i >= 0; i--)
{
char let = value[i];
if (let == '?' ||
let == '!' ||
let == '.')
{
removeLength++;
}
else
{
break;
}
}
if (removeLength > 0)
{
return value.Substring(0, value.Length - removeLength);
}
return value;
}
Output
Input string:
const string input = "The Dev Codes!?!...";
Notes:
TrimEnd version was called with a cached params array.
TrimTrailingChars: 34.87 ns
TrimEnd: 74.25 ns