How to return a string format with C #?

1

I have the following value.

String dato="SDI87H";

And I wish to return SD-I8-7H

I've tried with

 String.Format("{0:##-##-##}", dato);

But it is not, since the value that must be delivered is numeric, but in this case I must deliver a string, so I can add hyphens.

I would like to know the format or regular expression of how to do the return in the desired format that I have outlined in the example.

    
asked by Danilo 05.09.2017 в 03:45
source

3 answers

3

The format function is used to format numbers and dates in standard things. In your case, there is no function to format strings. However, you can arm yourself the chain by concatenating the pieces.

In your case, something like this would return the chain you are looking for.

String datonuevo = dato.Substring(0,2) + "-" + dato.Substring(2,2) + "-" + dato.Substring(4);
    
answered by 05.09.2017 / 03:52
source
2

Or you can use this awful feature ... (do not judge me I'm bored)

recursiva("SDI87H", 0, 2, "-");

public StringBuilder sb { set; get; }

public void recursiva(string cadena, int indiceInicialCorte, int tajada, string caracteres)
{
    //sb = new StringBuilder();
    if (sb == null)
    {
        sb = new StringBuilder();
    }

    if (indiceInicialCorte + tajada < cadena.Length)
    {
        sb.Append(cadena.Substring(indiceInicialCorte, tajada) + caracteres);
        //micadena += cadena.Substring(indiceInicialCorte, tajada) + caracteres;
        recursiva(cadena, indiceInicialCorte + tajada, tajada, caracteres);
    }
    else
    {
        sb.Append(cadena.Substring(indiceInicialCorte, tajada - (indiceInicialCorte + tajada - cadena.Length)));
        //micadena += cadena.Substring(indiceInicialCorte, tajada - (indiceInicialCorte + tajada - cadena.Length));
    }

    micadena = sb.ToString();
}
    
answered by 05.09.2017 в 06:59
1

Another option using LINQ, which basically divides the input string into groups of 2 characters and then joins them with a - script:

var datoformat = String.Join("-",Enumerable.Range(0, dato.Length / 2)
                             .Select(x => dato.Substring(x*2, 2)).ToArray()
                            );

To use this solution, keep in mind that the input string is multiples of 2, otherwise you will not discard the last character

    
answered by 05.09.2017 в 10:39