String trim
In this chapter you will learn:
- Use the Trim(), TrimStart(), and TrimEnd() methods to trim strings
- Trim white space
- Trim #s from String
Trim a string
Trim, TrimStart, TrimEnd
remove specified characters from a string.TrimStart
removes the characters from the start of a string.TrimEnd
deletes the characters from the end of a string.Trim
does the trim from both ends.
using System;/*java2 s . c om*/
class Sample
{
public static void Main()
{
string s = " java2s.com ";
Console.WriteLine("=" + s.Trim() + "=");
Console.WriteLine("=" + s.TrimStart() + "=");
Console.WriteLine("=" + s.TrimEnd() + "=");
}
}
The output:
Trim white space
By default these functions remove while spaces including tabs and new lines. We can passin characters to those functions.
using System;//from j a va 2s. co m
class Sample
{
public static void Main()
{
string s = "java2s.com";
Console.WriteLine("=" + s.Trim('m') + "=");
Console.WriteLine("=" + s.TrimStart('j') + "=");
Console.WriteLine("=" + s.TrimEnd('m') + "=");
}
}
The output:
Trim #s from String
using System;// j a v a 2 s . c o m
class MainClass {
public static void Main() {
string str = " test ";
Console.WriteLine("Original string:" + str+"<");
// Pad on right with #s.
str = str.PadRight(20, '#');
Console.WriteLine("|" + str + "|");
// Trim #s.
str = str.Trim('#');
Console.WriteLine("|" + str + "|");
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » String