create a function that gets the last n characters in a string in csharp

To get the last n characters of a string in C#, you can use the Substring method along with the Length property of the string. Here is an example:

main.cs
public static string GetLastNCharacters(string inputString, int n)
{
    if (n >= inputString.Length)
    {
        return inputString; // Return the entire string
    }
    else
    {
        return inputString.Substring(inputString.Length - n); // Substring starting from the last n characters
    }
}
304 chars
12 lines

This GetLastNCharacters function takes two arguments - inputString and n. It first checks if the length of the string is less than n. If yes, then it returns the entire string. If the length of the string is greater than n, it uses the Substring method along with Length property to get the last n characters of the string.

You can use this function like this:

main.cs
string inputString = "Hello, World!";
int n = 3;
string result = GetLastNCharacters(inputString, n);
Console.WriteLine(result); // Outputs "ld!"
145 chars
5 lines

This will output the last n characters of the inputString.

gistlibby LogSnag