Getting the last 3 characters To access the last 3 characters of a string, we can use the built-in Substring() method in C#. In the above example, we have passed s. Length-3 as an argument to the Substring() method.
string str = (yourStringVariable + " "). Substring(0,5). Trim();
The start index of your substring is then equal to the number of words that occured before your substring. We can find this amount by splitting the string before your first match in words and counting the number of words. The end index is the start index augmented by the number of words in your substring.
If your input string could be less than five characters long then you should be aware that string.Substring
will throw an ArgumentOutOfRangeException
if the startIndex
argument is negative.
To solve this potential problem you can use the following code:
string sub = input.Substring(Math.Max(0, input.Length - 5));
Or more explicitly:
public static string Right(string input, int length)
{
if (length >= input.Length)
{
return input;
}
else
{
return input.Substring(input.Length - length);
}
}
string sub = input.Substring(input.Length - 5);
If you can use extension methods, this will do it in a safe way regardless of string length:
public static string Right(this string text, int maxLength)
{
if (string.IsNullOrEmpty(text) || maxLength <= 0)
{
return string.Empty;
}
if (maxLength < text.Length)
{
return text.Substring(text.Length - maxLength);
}
return text;
}
And to use it:
string sub = input.Right(5);
static void Main()
{
string input = "OneTwoThree";
//Get last 5 characters
string sub = input.Substring(6);
Console.WriteLine("Substring: {0}", sub); // Output Three.
}
Substring(0, 3)
- Returns substring of first 3 chars. //One
Substring(3, 3)
- Returns substring of second 3 chars. //Two
Substring(6)
- Returns substring of all chars after first 6. //Three
One way is to use the Length
property of the string as part of the input to Substring
:
string sub = input.Substring(input.Length - 5); // Retrieves the last 5 characters of input
Here is a quick extension method you can use that mimics PHP syntax. Include AssemblyName.Extensions
to the code file you are using the extension in.
Then you could call:
input.SubstringReverse(-5) and it will return "Three".
namespace AssemblyName.Extensions {
public static class StringExtensions
{
/// <summary>
/// Takes a negative integer - counts back from the end of the string.
/// </summary>
/// <param name="str"></param>
/// <param name="length"></param>
public static string SubstringReverse(this string str, int length)
{
if (length > 0)
{
throw new ArgumentOutOfRangeException("Length must be less than zero.");
}
if (str.Length < Math.Abs(length))
{
throw new ArgumentOutOfRangeException("Length cannot be greater than the length of the string.");
}
return str.Substring((str.Length + length), Math.Abs(length));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With