titani12
titani12

Reputation: 5

Get the two first and last chars of a string C#

Well I'd like to get the two first and last chars of a string. This is what I already got

public static string FirstLastChars(this string str)
{
    return str.Substring(0,2);
}

BTW. It's an extension method

Upvotes: 0

Views: 2861

Answers (4)

Surbhi Khandelwal
Surbhi Khandelwal

Reputation: 11

Try this code-

 static void Main(string[] args)
    {
        int[] numbers = { 12, 34, 64, 98, 32, 46 };
        var finalList = numbers.Skip(2).SkipLast(2).ToArray();

        foreach(var item in finalList)
        {
            Console.WriteLine(item + "");
        }
    }

Upvotes: 0

Peter Csala
Peter Csala

Reputation: 22849

As an alternative you can make use of the Span Api.

First you need to create a buffer and pass that to a Span instance. (With this you have a writable Span.)

var strBuffer = new char[3];
var resultSpan = new Span<char>(strBuffer);

From the original str you can create two ReadOnlySpan<char> instances to have references for the first two letters and for the last letter.

var strBegin = str.AsSpan(0, 2);
var strEnd = str.AsSpan(str.Length - 1, 1);

In order to make a single string from two Span objects you need to concatenate them. You can do this by making use of the writable span.

strBegin.CopyTo(resultSpan.Slice(0, 2));
strEnd.CopyTo(resultSpan.Slice(2, 1));

Finally let's convert the Span<char> into string. You can do this in several ways, but the two most convenient commands are the followings:

  • new string(resultSpan)
  • resultSpan.ToString()

Helper:

public static class StringExtentions
{
    public static string FirstLastChars(this string str)
    {
        if (str.Length < 4) return str;

        var strBuffer = new char[3];
        var resultSpan = new Span<char>(strBuffer);

        var strBegin = str.AsSpan(0, 2);
        var strEnd = str.AsSpan(str.Length - 1, 1);

        strBegin.CopyTo(resultSpan.Slice(0, 2));
        strEnd.CopyTo(resultSpan.Slice(2, 1));

        return new string(resultSpan);
    }
}

Usage:

class Program
{
    static void Main(string[] args)
    {
        string str = "Hello World!";
        Console.WriteLine(str.FirstLastChars()); //He!
    }
}

Upvotes: 0

Athanasios Kataras
Athanasios Kataras

Reputation: 26450

Starting C# 8.0 you can use array ranges:

public static class StringExtentions {
    public static string FirstLastChars(this string str)
    {
       // If it's less that 4, return the entire string
       if(str.Length < 4) return str;
       return str[..2] + str[^2..];
    }
}

Check solution here: https://dotnetfiddle.net/zBBT3U

Upvotes: 3

lukai
lukai

Reputation: 576

You can use the existing string Substring method. Check the following code.

public static string FirstLastChars(this string str)
{
    if(str.Length < 4)
    {
      return str;
    }
    return str.Substring(0,2) + str.Substring(str.Length - 1, 1) ;
}

Upvotes: 1

Related Questions