简体   繁体   中英

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

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

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

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

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 + "");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM