C#8索引和范围(数组切片)

/// <summary>
/// 正序下标从零开始
/// 倒序下标从一开始
/// </summary>
public void Demo3()
{
    // 正序下标从零开始
    // 倒序下标从一开始
    var words = new string[]
    {
        // index from start, index from end
        "The",      // 0, ^9
        "quick",    // 1, ^8
        "brown",    // 2, ^7
        "fox",      // 3, ^6
        "jumped",   // 4, ^5
        "over",     // 5, ^4
        "the",      // 6, ^3
        "lazy",     // 7, ^2
        "dog"       // 8, ^1
    };

    //取最后一个元素
    Console.WriteLine($"The last word is {words[^1]}");//dog

    //获取下标是一的元素到下标是三的元素
    var quickBrownFox = words[1..4];
    Console.WriteLine(quickBrownFox);//quick,brown,fox

    //获取倒数第二个元素到倒数第一个元素
    var lazyDog = words[^2..^0];
    Console.WriteLine(lazyDog);//lazy,dog

    //获取倒数第二个元素到结束
    var lazyDog2 = words[^2..];
    Console.WriteLine(lazyDog2);//lazy,dog

    //获取全部元素
    var all = words[..];
    Console.WriteLine(all);

    //获取开始到下标是四的元素
    var firstPhrase = words[..4];
    Console.WriteLine(firstPhrase);//The,quick,brown,fox

    //获取下标是六的元素到结束
    var lastPhrase = words[6..];
    Console.WriteLine(lastPhrase);//the,lazy,dog
}

 

上一篇:c – 如何在Qt中模拟崩溃?


下一篇:c – 如何使用QWebEngineUrlRequestInterceptor