How to break line after 29 digits C#?

Asked

Viewed 283 times

0

How do I make every 29 digits the line break?

var hs = hs_codes.Text;
        var texto = new StringBuilder(hs.Length);
        var digito = true;

        foreach(var chr in hs)
        {
            if (char.IsDigit(chr))
            {
                if (!digito) texto.Append(';');
                texto.Append(chr);
                digito = true;
            }
            else digito = false;
        }
        txt_alterado.ReadOnly = false;
        txt_alterado.Focus();

        txt_alterado.Text = Convert.ToString(texto);
  • Break up like?

  • every 29 digits it breaks in the textbox, I’m not able to do with /n/r

  • TextBox does not deal with line break.

  • One should use a RichTextBox with the property MultiLine = true.

3 answers

0

Friend I’m not sure anymore try something like this.... Don’t forget to enable multiline

    var hs = hs_codes.Text;
    var texto = new StringBuilder(hs.Length);
    var digito = true;
    int i = 0; 
    foreach(var chr in hs)
    {
        if (char.IsDigit(chr))
        {

            if (!digito) texto.Append(';');
            texto.Append(chr);
            digito = true;
            if(i>27){
                i=0;
                texto.Append(Environment.NewLine);
            }
            i++;
        }
        else digito = false;
    }
    txt_alterado.ReadOnly = false;
    txt_alterado.Focus();

    txt_alterado.Text = Convert.ToString(texto);

0

You can do using LINQ

For example:

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string strText = "1234567890" + 
                         "ABCDEFGHIJ" + 
                         "1234567890" + 
                         "abcdefghij" + 
                         "1234567890";

        const int qtdQuebra = 10;
        var arrayTxrt = strText.Select((e, i) => ((i + 1) % qtdQuebra == 0) ? e + Environment.NewLine : e.ToString());  
        Console.WriteLine(string.Join("", arrayTxrt));
    }
}

See working on . NET Fiddle

0

You can use the Take (using the library System.Linq) to get just the number of characters you want, and go adding the line-breaking text to the TextBox:

// exemplo com texto fixo
string strText = "quebra de linha aos 29 caracteres; vamos ver se o código funciona em TextBox com Multiline = True!";

while (true)
{
    textBox1.AppendText($"{string.Concat(strText.Take(29))}{Environment.NewLine}");

    if (strText.Length >= 29)
        strText = strText.Substring(29);
    else break;
}

Can be a control TextBox, but you must have the property Multiline activated.
Based on this example only need then adapt to your needs!

Browser other questions tagged

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