Get the last N characters of a string

4

I have string which is actually a phone number . But a phone number might have some formats like:

+55 34 98989898

34 989898

989898

The constant is that always the last 8 numbers are the phone numbers, I wanted to know how I separate these last 8 numbers from the rest. Example:

numero = "+55 34 98989898"

Turning

n1 = "+55 34 ";
n2 = "98989898";

Could you use the SubString ? And how?

    
asked by anonymous 08.10.2015 / 21:23

3 answers

3

If it's in this format:

string telefone = "+55 34 98989898";

Console.WriteLine(telefone.Substring(telefone.Length - 8));

Demo Link

    
08.10.2015 / 21:37
4
  

The constant is that always the last 8 numbers are the numbers of the   phone, I wanted to know how I separate these last 8 numbers from the   remaining.

Use Substring using as parameter the size of your variable minus the number of characters you want to capture.

Remember before checking that the size of string contains the desired number of characters.

public class Program
{
    public static void Main()
    {
        var telefone = "123 12345678";
        Console.WriteLine(telefone);        
        if(telefone.Length > 8) 
               Console.WriteLine(telefone.Substring(telefone.Length -8)); //12345678
    }
}

FIDDLE net code link

  

number="+55 34 98989898"

     

Turn n1="+55 34"; n2="98989898";

If your variable always contains this format, you can use the Split method using space as a parameter:

public static void Main()
    {
        var telefone = "+55 81 12345678";
        Console.WriteLine(telefone);    

        var telefoneSeparado = telefone.Split(' ');

        Console.WriteLine("CD País: " + telefoneSeparado[0]); //+55     
        Console.WriteLine("DDD: " + telefoneSeparado[1]); //81      
        Console.WriteLine("Número: " + telefoneSeparado[2]); //12345678
    }

FIDDLE .net code: link

If your variable does not have a specific format, you can use the String.Remove method that works similarly to String.Substring

public static void Main()
    {
        var telefone = "+55 81 12345678";
        Console.WriteLine(telefone); //+55 81 12345678      

        Console.WriteLine(telefone.Substring(telefone.Length -8)); //2345678

        Console.WriteLine(telefone.Remove(telefone.Length - 8)); //+55 81 

    }

Code working in .NET Fiddle link

    
08.10.2015 / 21:40
4

I like the regular expression approach.

var regex = new Regex(@"([\d]{8})");
var match = regex.Match("+55 34 98989898");
if (match.Success)
{
    Console.WriteLine(match.Value); // Imprime "98989898"
}
    
08.10.2015 / 22:52