Search code examples
c#linqsubstring

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).

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