How to remove blank line "Return"

Asked

Viewed 1,534 times

0

I have a TextBox where the user will type.

I cannot leave any blank line (Return " r") before sending to the database. In my code, it works well when you find \r\r, but not when they have \r\r\r

How can I fix this?

The text should look like this:

exemplo
exemplo
exemplo

Not like this:

exemplo


exemplo

exemplo
exemplo

Code:

     while (insObs.Text != "")
     {
         if (insObs.Text.Contains("\r\r"))
         {
            vaiObs = insObs.Text.Replace("\r\r", "\r");
             break;
         }

     }

2 answers

3


You are running the loop only once, so it overwrites only the direct occurrences of \r\r, but when removing one of the Returns what remains concatenates with the next.

Change your code snippet to:

vaiObs = insObs.Text;
while (vaiObs.Text.Contains("\r\r"))
{
    vaiObs = vaiObs.Text.Replace("\r\r", "\r");
}

1

A good alternative would be to use regex! See:

            using System;
        using System.Text.RegularExpressions;
        namespace teste
        {
            class Program
            {
                static void Main(string[] args)
                {

                    string[] itens = { "exemplo1", "\r", "exemplo3", "exemplo4", "\r", "\r\r\r\r", "exemplo7", "exemplo8" };
                    Regex r = new Regex(@"\r",RegexOptions.IgnoreCase);
                    foreach (string e in itens)
                        if(!r.IsMatch(e))
                            Console.WriteLine(e);
                }
            }
        }

See working in practice:

http://ideone.com/8zo4Nh

Reference: System.Text.Regularexpressions

Regex.Match method (String)

Browser other questions tagged

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