C# WPF How to separate a long string into several positions of an Array?

Asked

Viewed 166 times

-1

I need to create a getter and a Setter for 14 Model properties that will be used to make Binding in Xaml. The properties come from here: I have a field from a database table where it loads a very long string that contains information for 14 textboxes on my screen (userControl). The string must be "broken" into 14 parts of 50 characters, each part of 50 characters must be a position within an array. The getter separates the string and the Setter joins it again. That’s all I know about this data. For now I have this getter method, but it seems incomplete (I can not see very well what is missing because I am new to both programming and language - I admit I stuck and I do not know what to do)

public string[] GetFlagInJobMvTit(int startPosition, int stringLength)
    {
        StringBuilder sbJobMvTit = new StringBuilder(50);
        startPosition = 0;

        string[] TitArray = new string[14];
        for (int i=0; i < 14; i++)
        {
            JobMvTit = sbJobMvTit.ToString();
            NotifyPropertyChanged("job_mv_tit");
            TitArray[i] = JobMvTit;
            startPosition += stringLength;
        }
        return TitArray;
    }

Thank you in advance

  • Your question seems incomplete; it actually seems to have a lot of irrelevant information, but it lacks what you’re doubting, what we can help. Giving an analyzed the code seems to make no sense, but it may be just that I didn’t understand objective.

4 answers

1

Simple way to split the string using regular expressions, remembering that with substring always have to validate the size, if the string is smaller than 14*50 there will be error.

var stringGiganteDoBanco = "123141231231245123124512312312451231245124312412341212314123123124512312451231231245123124512431241234121231412312312451231245123123124512312451243124123412";

var arrayStrings = Regex.Split(stringGiganteDoBanco, "(?<=\\G.{50})");
  • I didn’t know Regex did it. Very good your answer. : the

  • Regex does magic ;)

0

I also found your doubt somewhat incomplete, but I believe you’re looking for something like this:

public string[] DividirString(string str)
{
    if(str.Length != 50*14)
        throw new ArgumentException("String inválida", "str");

    var partes = new string[14];
    for (int parteAtual = 0, i = 0; parteAtual < 14; parteAtual++)
    {
        partes[parteAtual] = str.Substring(i, 50);
        i += 50;
    }

    return partes;
}

0

I made this kind of example, which meets your need. I have not done error treatments, nor the origin of the data.

        public class Teste
        {
            public Teste()
            {
                //Chamo o método de carregar a List<>
                Carregar();
            }

            //String de exemplo com tamanho 700
            string textoMuitoGrande = "".PadRight(50, 'A') + "".PadRight(50, 'B') + "".PadRight(50, 'C') + "".PadRight(550, 'X');

            //Lista que armazena todas as propriedades
            List<string> _propriedades;

            //Encapsulamento propriedade A
            public string PropriedadeA { get { return _propriedades[0]; } set { _propriedades[0] = value; } }

            //Encapsulamento propriedade B
            public string PropriedadeB { get { return _propriedades[1]; } set { _propriedades[1] = value; } }


            //Método para obter todo o conteúdo da string concatenada
            public string JuntarTudo()
            {
                string retorno = "";
                foreach (string s in _propriedades)
                    retorno += s;

                return retorno;
            }

            //Método que divide a string e carrega a List<>
            public void Carregar()
            {
                _propriedades = new List<string>();
                int x = 0;
                for (int i =0; i < 14;i++)
                {
                    _propriedades.Add(textoMuitoGrande.Substring(x, 50));
                    x += 50;
                }
            }
        }

0

You can create a string extension method to help with this task.

using System;
using System.Collections.Generic;

namespace StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            string helloWorld = "Hello World! Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!";
            var stringDivided = helloWorld.SplitParts(10);
            foreach (var part in stringDivided)
            {
                Console.WriteLine($"{ part }\n");
            }
            Console.ReadKey();
        }
    }

    public static class StringExtensions
    {
        public static IEnumerable<String> SplitParts(this String s, Int32 partLength)
        {
            if (s == null)
                throw new ArgumentNullException("s");
            if (partLength <= 0)
                throw new ArgumentException("Part must be positive.", "partLength");

            for (var i = 0; i < s.Length; i += partLength)
                yield return s.Substring(i, Math.Min(partLength, s.Length - i));
        }
    }
}

Browser other questions tagged

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