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

Best way to get a substring when knowing the last index and how many characters to take before that in C#

Say I have a string abcdefghi

I would like to extract from that the string cdef

I know that the index of the last character I want is 5 (which is f).

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

I also know that I want to take the 3 preceding characters with it.

Here is my code so far, which does work, but doesn’t look that pretty. Is there a better way?

string text = "abcdefghi";
int lastIndex = 5;
int numberOfCharsToTake = 4  // including the last index char

Console.WriteLine(
    string.Join("",
    text
    .Substring(0, lastIndex + 1)
    .Reverse()
    .Take(numberOfCharsToTake)
    .Reverse()
    )
)

>Solution :

string text = "abcdefghi";
string lastIndex = 5;
string numberOfCharsToTake = 4  // including the last index char

Console.WriteLine(
    text.Substring(lastIndex - numberOfCharsToTake, numberOfCharsToTake)
);
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