How to separate sequence of numbers in an array

Asked

Viewed 197 times

2

For example, the user places in a textarea "1234 5678 1011 1213" I made a system that puts point and comma in each space, now I need to know how to store a digit sequence in an array, so I can make a code that after 6 sequences, skip a line.

For example, the user type: 1090 5411 1006 / 6061 - 4025 4587 6518 / 7892

System already modifies to: 1090;5411;1006;6061;4025;4587;6518;7892

And I wish that every six sequences of numbers, he would skip one line: 1090;5411;1006;6061;4025;4587; 6518;7892

private void btnHSCode_Click(object sender, EventArgs e)
        {
            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 = texto.ToString();

        }

1 answer

1

Use static class method Regex Replace(String, String, String) to make the replacements. What is not digit it replaces with ";" and then places a line break after six sequences of digits ended by ";"

using System.Text.RegularExpressions;



private void btnHSCode_Click(object sender, EventArgs e)
{
     txt_alterado.ReadOnly = false;
     txt_alterado.Focus();

     txt_alterado.Text = 
          Regex.Replace(Regex.Replace(hs_codes.Text, @"[^\d]+", ";"), @"(\d+;){6}", "$0\n");

 }
  • Then to separate into String[] use the method String.Split(char) using ';' as parameter. var strarr = txt_alterado.Text.Split(';');

Browser other questions tagged

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