Skip to content
Advertisement

String Slicing in c# using intervals

In python there are ways that allow you to access the string using an interval(slicing):

Example Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Is there something similar in c#?

Advertisement

Answer

In C# 8.0 (or higher) you can use ranges, e.g

var b = "Hello, World!";

var result = b[2..5];

Or on old c# versions, Substring:

var b = "Hello, World!";

// start from 2nd char (0-based), take 3 characters
var result = b.Substring(2, 3);

Finally, you can use Linq, but it’s overshoot here:

var b = "Hello, World!";

// Skip first 2 characters, take 3 chars and concat back to the string 
var result = string.Concat(b
    .Skip(2)
    .Take(3));
Advertisement