String trim

In this chapter you will learn:

  1. Use the Trim(), TrimStart(), and TrimEnd() methods to trim strings
  2. Trim white space
  3. 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:

  1. How to intern a string
Home » C# Tutorial » String
string
String creation
Char in string
Compare strings
String equality
String concatanation
String copy
String Join
String split
String Search for Index
String contains
String start with
String insert
String case
Replacing substring
Remove from a string
Substring
Escape Characters
String verbatim
String padding
Switch on String
String trim
String intern
String normalization
Empty String