How to remove blank line "Return"

0

I have a TextBox where the user will type.

I can not leave any blank lines (return "\ r") before sending them to the database. In my code, it works fine when it finds \r\r , but not when \r\r\r

How can I resolve 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;
         }

     }
    
asked by anonymous 03.03.2015 / 18:54

2 answers

3

You are running the loop only once, so it replaces only the direct occurrences of \r\r , but when removing one of the surplus returns 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");
}
    
03.03.2015 / 19:05
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:

link

Reference:   System.Text.RegularExpressions

Regex.Match Method (String)

    
03.03.2015 / 20:50