How can I extract a substring which is composed of the rightmost six letters from another string?
Ex: my string is "PER 343573". Now I want to extract only "343573".
How can I do this?
How can I extract a substring which is composed of the rightmost six letters from another string?
Ex: my string is "PER 343573". Now I want to extract only "343573".
How can I do this?
Use this:
String text = "PER 343573";
String numbers = text;
if (text.Length > 6)
{
numbers = text.Substring(text.Length - 6);
}
Probably nicer to use an extension method:
public static class StringExtensions
{
public static string Right(this string str, int length)
{
return str.SubString(str.Length - length, length);
}
}
Usage
string myStr = "PER 343573";
string subStr = myStr.Right(6);
String mystr = "PER 343573";
String number = mystr.Substring(mystr.Length-6);
EDIT: too slow...
Write an extansion method to express the Right(n);
function. The function should deal with null or empty strings returning an empty string, strings shorter than the max length returning the original string and strings longer than the max length returning the max length of rightmost characters.
public static string Right(this string sValue, int iMaxLength)
{
//Check if the value is valid
if (string.IsNullOrEmpty(sValue))
{
//Set valid empty string as string could be null
sValue = string.Empty;
}
else if (sValue.Length > iMaxLength)
{
//Make the string no longer than the max length
sValue = sValue.Substring(sValue.Length - iMaxLength, iMaxLength);
}
//Return the string
return sValue;
}
This isn't exactly what you are asking for, but just looking at the example, it appears that you are looking for the numeric section of the string.
If this is always the case, then a good way to do it would be using a regular expression.
var regex= new Regex("\n+");
string numberString = regex.Match(page).Value;
Guessing at your requirements but the following regular expression will yield only on 6 alphanumerics before the end of the string and no match otherwise.
string result = Regex.Match("PER 343573", @"[a-zA-Z\d]{6}$").Value;
Without resorting to the bit converter and bit shifting (need to be sure of encoding) this is fastest method I use as an extension method 'Right'.
string myString = "123456789123456789";
if (myString > 6) {
char[] cString = myString.ToCharArray();
Array.Reverse(myString);
Array.Resize(ref myString, 6);
Array.Reverse(myString);
string val = new string(myString);
}