How to remove spaces at the beginning and end of a string?

Asked

Viewed 7,228 times

4

How to remove any number of spaces at the beginning or end of a C string#?

  • Have you made any attempt? What was the result of your attempt?

2 answers

10


Utilize String.Trim():

"    aaa    ".Trim()
// "aaa"

To remove only spaces in beginning of the string, use String.Trimstart()

"    aaa    ".TrimStart()
// "aaa    "

To remove only spaces in end of the string, use String.Trimend()

"    aaa    ".TrimEnd()
// "    aaa"

0

Well, only at the beginning or end is it like the Fábio Perez said, but every sentence can be like this:

string frase = "Isso é uma string"; // Declaramos a string
string sem = ""; // Declaramos o futuro resultado
foreach (char c in frase.ToCharArray()) // Para cada 'letra' na frase
{
    if (c != ' ') // Se a letra não for um espaço
        sem += c; // É adicionada a string final
}
Console.WriteLine(sem); // Escrevemos a string final no console

That gives the result:

This is a string

Browser other questions tagged

You are not signed in. Login or sign up in order to post.