Get the last N characters from a string

Asked

Viewed 9,903 times

4

I have a string which in reality is a phone number. But a phone number can have some formats like:

+55 34 98989898

34 989898

989898

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

numero = "+55 34 98989898"

Turn

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

Could use the Substring? And how?

  • Don’t know how to use Substring? That would be it?

  • In that case, no, I don’t know how I’m going to take the last 8 characters as a reference

3 answers

4

The constant is that always the last 8 numbers are the numbers of the phone, I wonder how I separate these last 8 numbers from the remainder.

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

Remember before checking if the size of the string contains the amount of characters desired.

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
    }
}

Code in. net FIDDLE https://dotnetfiddle.net/CMAnYN

number = "+55 34 98989898"

Turn n1 = "+55 34 "; N2 = "989898";

If your variable always contains this format, you can use the method Split 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
    }

Code in. net FIDDLE: https://dotnetfiddle.net/4qHIJM

If your variable does not have a specific format, you can use the method String.Remove works in a similar way 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 on . NET Fiddle https://dotnetfiddle.net/Hna8yD

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"
}

3


If it’s in that format:

string telefone = "+55 34 98989898";

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

Link to the Demo

Browser other questions tagged

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