c# - How to remove white spaces from a string

String remove whitespace
The following asp.net c# example code demonstrate us how can we remove white space from a string object programmatically at run time in an asp.net application. String represent a series of Unicode characters. String Class does not have any method or property to identify white space/blank space in its value. So. at first we need to convert string value to Char objects.

String.ToCharAray() method allow us to copies the characters in a string instance to a Unicode character array. Then, we can loop through the characters array to determine which character is a white space. In this example, we loop through the char array using foreach loop.

Char.IsWhiteSpace(Char) overloaded method indicate whether a specified Unicode character is categorized as white space/empty space. So, by the way we can test each character of string that which represent white space. Then we can remove the specified characters from string object. Finally, we get a string where whitespaces are removed/deleted.

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
        //this section create a string variable.
        string characters = "A B C D E F";

        Label1.Text = "string of characters..................<br />";
        Label1.Text += characters + "<br /><br />";

        char[] chars = characters.ToCharArray();

        characters = "";
        foreach(char c in chars)
            if (char.IsWhiteSpace(c))
                Label1.Text += "whitespace";
                Label1.Text += c.ToString();
                characters += c;
            Label1.Text += "<br />";

        Label1.Text += "<br />after removing white spaces from string...........<br />";
        Label1.Text += characters;
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string remove whitespace</title>  
    <form id="form1" runat="server">  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string remove whitespace
        <hr width="550" align="left" color="Gainsboro" />  
        <br /><br />
            Text="string remove whitespace"  
More c# examples