【.Net Core/.Net8教程】巧用 C# 8.0 切片语法:高效处理数组和字符串

    C# 切片语法糖(使用 .. 和 ^)是在 C# 8.0 版本中引入的。这些新语法提供了更简洁的方式来对数组、字符串和其他实现了 System.Span<T> 接口的类型进行切片和索引操作。

1. 使用 ^ 表示从尾部索引

^ 符号用于从集合的尾部开始索引。

int[] array = { 10, 20, 30, 40, 50 };

// 取得最后一个元素
int lastElement = array[^1]; // 50

// 取得倒数第二个元素
int secondLastElement = array[^2]; // 40

2. 使用 .. 表示范围

范围操作符 .. 可以用于获取集合的子范围。

int[] array = { 10, 20, 30, 40, 50 };

// 取得前两个元素
int[] firstTwo = array[..2]; // { 10, 20 }

// 取得从索引 2 开始到末尾的元素
int[] fromThirdToEnd = array[2..]; // { 30, 40, 50 }

// 取得中间的元素(索引 1 到 3,不包括 3)
int[] middle = array[1..3]; // { 20, 30 }

3. 获取整个数组

可以使用 .. 不带任何参数来获取整个数组。

int[] array = { 10, 20, 30, 40, 50 };

// 返回整个数组
int[] allElements = array[..]; // { 10, 20, 30, 40, 50 }

4. 从特定索引开始到倒数索引结束

组合使用索引和范围。

int[] array = { 10, 20, 30, 40, 50 };

// 从索引 1 到倒数第二个元素(不包括倒数第一个)
int[] range = array[1..^1]; // { 20, 30, 40 }

5. 字符串切片

这些操作同样适用于字符串。

string text = "foolisunday 原创自八荒我为王@youkuaiyun.com";

// 取得前 11 个字符
string hello = text[..11]; // "foolisunday"

// 取得最后 9 个字符
string world = text[^9..]; // "@youkuaiyun.com"

// 取得从索引 12 开始到倒数第 9 个字符的范围
string subText = text[12..^9]; // "原创自八荒我为王"

6. 带有 Range 类型的复杂表达式

C# 中的 Range 类型可以用于创建自定义范围,并用于传递给方法。

int[] array = { 10, 20, 30, 40, 50 };

// 使用 Range 对象
Range customRange = 1..4;
int[] subArray = array[customRange]; // { 20, 30, 40 }

7. 带有 Index 类型的表达式

Index 类型允许创建基于正向或反向的索引。

int[] array = { 10, 20, 30, 40, 50 };

Index lastIndex = ^1;
int lastElement = array[lastIndex]; // 50

Index startIndex = 2;
int startElement = array[startIndex]; // 30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值