How to break line after 29 C # digits?

0

How do I do that every 29 digits, the line breaks?

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);
    
asked by anonymous 08.08.2018 / 23:50

3 answers

0

Friend not sure yet try something like this .... Do not 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);
    
09.08.2018 / 01:31
0

You can use Take (using the System.Linq library) to get only the number of characters you want, and then add the wrapped text to 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;
}

It may be a% control of%, but must have the TextBox property enabled.
Based on this example you only need to adapt to your needs!

    
09.08.2018 / 10:46
0

You can do this 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 in .NET Fiddle

    
09.08.2018 / 22:19