Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading