How do I remove white space from text?

5

I was trying to get whitespace from a string , but .Trim() does not work, this still displays whitespaces:

 var teste = texto.Trim();
 txtConteudo.Text = teste;

For example, if it receives: "text text", it continues: "text text" even after passing Trim . Should not it show "texttext"? How do I get this result?

    
asked by anonymous 07.10.2015 / 14:12

2 answers

10

There are 3 methods for cutting spaces, you can cut at the beginning, at the end, or both. You have to use the correct one for what you want. It is still possible to cut all. The example shown in the question indicates using the wrong method:

using static System.Console;

public class Program {
    public static void Main() {
        var texto = " Hello World ";
        WriteLine($"Corta o fim: |{texto.TrimEnd()}|");
        WriteLine($"Corta o início: |{texto.TrimStart()}|");
        WriteLine($"Corta ambos: |{texto.Trim()}|");
        WriteLine($"Corta tudo: |{texto.Replace(" ", "")}|");
    }
}

See working on dotNetFiddle .

07.10.2015 / 14:24
1

The Trim function only removes the whitespace that is contained at the beginning and end of the string, ie the whitespace that exists within the string will not be removed.

var texto = " Texto a ser removidos seus espaços. ";

//Trim() remove os espaços do inícil e do fim da string.
var trimTexto = texto.Trim();//Output: "Texto a ser removidos seus espaços."

//TrimStart() remove os espaços somente do inícil da string.
var trimTexto2 = texto.TrimStart();//Output: "Texto a ser removidos seus espaços. "

//TrimEnd() remove os espaços somente do fim da string.
var trimTexto3 = texto.TrimEnd();//Output: " Texto a ser removidos seus espaços."
    
07.10.2015 / 14:35