Formatting Strings for RG

4

How can I format this String : 12345678x for this: 12.345.678-X? I tried to use String.Format but I could not.

Resolved:

public string RgFormat(object rg)
{   
    string strRg = rg.ToString();
    return strRg.Substring(0, 2) + "." + strRg.Substring(2, 3) + "." + strRg.Substring(5, 3) + "-" + strRg.Substring(8, 1).ToUpper();             
}

public string CpfFormat(object cpf)
{         
    string strCpf = cpf.ToString();
    return strCpf.Substring(0, 3) + "." + strCpf.Substring(3, 3) + "." +      strCpf.Substring(6, 3) + "-" + strCpf.Substring(9, 2).ToUpper();    
}
    
asked by anonymous 19.03.2015 / 19:49

3 answers

3

I can not see a better solution than this. I thought about using ToString() or string.Format() but I did not find an easy solution (it might have:

using System;

public class Program {
    public static void Main() {
        Console.WriteLine(FormataRG("12345678x"));
        Console.WriteLine(FormataRG("123456789"));
    }
    public static string FormataRG(string texto) {
        return texto.Substring(0, 2) + "." + texto.Substring(2, 3) + "." + texto.Substring(5, 3) + "-" + texto.Substring(8, 1).ToUpper();
    }
}

See working on dotNetFiddle .

Note that if it is RG same, each one may have a different format so this is not a universal solution. You have to identify the format before. Validation would already be another operation.

    
19.03.2015 / 20:03
2

An alternative to the @bigown response is to use Insert .

using System;

public class Program
 {
    public static void Main()
    {
        Console.WriteLine(mask("12345678x"));
    }

    public static string mask(string numbers) {
        return numbers.Insert(2, ".").Insert(6, ".").Insert(10, "-");
    }
 }

See working on @NET Fiddle .

    
19.03.2015 / 20:10
0

Try this out

Text1.Text = Text1.Text.Replace("X", "")

double numero;
if (Double.TryParse(Text1.Text, out numero))
      Text1.Text = numero.ToString(@"000\.000\.000\-X");
else
      MessageBox.Show("Valor inválido: " + Text1.Text);
    
19.03.2015 / 20:17