繁体   English   中英

获取字符串 C# 的第一个和最后一个字符

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

好吧,我想获取字符串的第一个和最后一个字符。 这是我已经得到的

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

顺便提一句。 这是一个扩展方法

从 C# 8.0 开始,您可以使用数组范围:

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..];
    }
}

在此处检查解决方案: https : //dotnetfiddle.net/zBBT3U

您可以使用现有的字符串 Substring 方法。 检查以下代码。

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

作为替代方案,您可以使用Span Api。

首先,您需要创建一个缓冲区并将其传递给Span实例。 (有了这个,你就有了一个可写的Span 。)

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

您可以从原始str创建两个ReadOnlySpan<char>实例,以引用前两个字母和最后一个字母。

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

为了从两个Span对象生成单个字符串,您需要将它们连接起来。 您可以通过使用可写跨度来做到这一点。

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

最后让我们将Span<char>转换为string 您可以通过多种方式执行此操作,但最方便的两个命令如下:

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

帮手:

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

用法:

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

试试这个代码-

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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