Home > Software design >  String Slicing in c# using intervals
String Slicing in c# using intervals

Time:07-15

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#?

CodePudding user response:

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-bazed), 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)); 

CodePudding user response:

You could use a substring.

string hw = "hello world";
Console.WriteLine(hw.Substring(1,1), hw.Substring(5, 1));

OR convert it into a char array

string hw = "hello world";
var array = hw.ToCharArray();
Console.WriteLine(array[3]);

CodePudding user response:

From c#8 you can use ranges:

b = "Hello, World!"
Console.WriteLine(b[2..5]

This prints:

llo

The best official guide is Indices and ranges.


When coming from Python, you should be aware of an important difference.

In Python:

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

llo, World!

In C#:

var b = "Hello, World!";
Console.WriteLine(b[2..15]);

Unhandled exception. System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. (Parameter 'length')
  • Related