Reputation: 218842
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?
Upvotes: 127
Views: 327720
Reputation: 104
You can use the Range Index to specify to get the last N characters from a string, the syntax is much cleaner and the code is shorter:
var text = "PER 343573";
var last6Characters = text[^6..];
What happens here is that using the square brackets [] you can get a substring from a text similar to the Substring function.
The first number represents the start, and the last number the end (not included).
Lear more here: Microsoft range indexes The same way it works with arrays, it works with a string because it is an array of characters.
Upvotes: 0
Reputation: 131
//Last word of string :: -> sentence
var str ="A random sentence";
var lword = str.Substring(str.LastIndexOf(' ') + 1);
//Last 6 chars of string :: -> ntence
var n = 6;
var right = str.Length >n ? str.Substring(str.Length - n) : "";
Upvotes: 0
Reputation: 82136
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);
Upvotes: 43
Reputation: 3376
var str = "PER 343573";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty
: str.Length < 6 ? str
: str.Substring(str.Length - 6); // "343573"
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // "343573"
this supports any number of character in the str
. the alternative code not support null
string. and, the first is faster and the second is more compact.
i prefer the second one if knowing the str
containing short string. if it's long string the first one is more suitable.
e.g.
var str = "";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty
: str.Length < 6 ? str
: str.Substring(str.Length - 6); // ""
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // ""
or
var str = "123";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty
: str.Length < 6 ? str
: str.Substring(str.Length - 6); // "123"
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // "123"
Upvotes: 5
Reputation: 748
//s - your string
//n - maximum number of right characters to take at the end of string
(new Regex("^.*?(.{1,n})$")).Replace(s,"$1")
Upvotes: 2
Reputation: 503
Just a thought:
public static string Right(this string @this, int length) {
return @this.Substring(Math.Max(@this.Length - length, 0));
}
Upvotes: 1
Reputation: 1768
Null Safe Methods :
Strings shorter than the max length returning the original string
String Right Extension Method
public static string Right(this string input, int count) =>
String.Join("", (input + "").ToCharArray().Reverse().Take(count).Reverse());
String Left Extension Method
public static string Left(this string input, int count) =>
String.Join("", (input + "").ToCharArray().Take(count));
Upvotes: 4
Reputation: 6693
Another solution that may not be mentioned
S.Substring(S.Length < 6 ? 0 : S.Length - 6)
Upvotes: 5
Reputation: 95
using Microsoft.visualBasic;
public class test{
public void main(){
string randomString = "Random Word";
print (Strings.right(randomString,4));
}
}
output is "Word"
Upvotes: 0
Reputation: 889
This is the method I use: I like to keep things simple.
private string TakeLast(string input, int num)
{
if (num > input.Length)
{
num = input.Length;
}
return input.Substring(input.Length - num);
}
Upvotes: 2
Reputation: 1861
I use the Min to prevent the negative situations and also handle null strings
// <summary>
/// Returns a string containing a specified number of characters from the right side of a string.
/// </summary>
public static string Right(this string value, int length)
{
string result = value;
if (value != null)
result = value.Substring(0, Math.Min(value.Length, length));
return result;
}
Upvotes: 0
Reputation: 5281
Since you are using .NET, which all compiles to MSIL, just reference Microsoft.VisualBasic, and use Microsoft's built-in Strings.Right
method:
using Microsoft.VisualBasic;
...
string input = "PER 343573";
string output = Strings.Right(input, 6);
No need to create a custom extension method or other work. The result is achieved with one reference and one simple line of code.
As further info on this, using Visual Basic methods with C# has been documented elsewhere. I personally stumbled on it first when trying to parse a file, and found this SO thread on using the Microsoft.VisualBasic.FileIO.TextFieldParser
class to be extremely useful for parsing .csv files.
Upvotes: 10
Reputation: 105
Use this:
string mystr = "PER 343573";
int number = Convert.ToInt32(mystr.Replace("PER ",""));
Upvotes: 3
Reputation: 3473
Here's the solution I use... It checks that the input string's length isn't lower than the asked length. The solutions I see posted above don't take this into account unfortunately - which can lead to crashes.
/// <summary>
/// Gets the last x-<paramref name="amount"/> of characters from the given string.
/// If the given string's length is smaller than the requested <see cref="amount"/> the full string is returned.
/// If the given <paramref name="amount"/> is negative, an empty string will be returned.
/// </summary>
/// <param name="string">The string from which to extract the last x-<paramref name="amount"/> of characters.</param>
/// <param name="amount">The amount of characters to return.</param>
/// <returns>The last x-<paramref name="amount"/> of characters from the given string.</returns>
public static string GetLast(this string @string, int amount)
{
if (@string == null) {
return @string;
}
if (amount < 0) {
return String.Empty;
}
if (amount >= @string.Length) {
return @string;
} else {
return @string.Substring(@string.Length - amount);
}
}
Upvotes: 2
Reputation: 351
using System;
public static class DataTypeExtensions
{
#region Methods
public static string Left(this string str, int length)
{
str = (str ?? string.Empty);
return str.Substring(0, Math.Min(length, str.Length));
}
public static string Right(this string str, int length)
{
str = (str ?? string.Empty);
return (str.Length >= length)
? str.Substring(str.Length - length, length)
: str;
}
#endregion
}
Shouldn't error, returns nulls as empty string, returns trimmed or base values. Use it like "testx".Left(4) or str.Right(12);
Upvotes: 27
Reputation: 13582
if you are not sure of the length of your string, but you are sure of the words count (always 2 words in this case, like 'xxx yyyyyy') you'd better use split.
string Result = "PER 343573".Split(" ")[1];
this always returns the second word of your string.
Upvotes: 11
Reputation: 57528
Write an extension 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;
}
Upvotes: 73
Reputation:
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);
}
Upvotes: 0
Reputation: 91
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;
Upvotes: 5
Reputation: 14513
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;
Upvotes: 9
Reputation: 46465
Use this:
String text = "PER 343573";
String numbers = text;
if (text.Length > 6)
{
numbers = text.Substring(text.Length - 6);
}
Upvotes: 6
Reputation: 19800
String mystr = "PER 343573";
String number = mystr.Substring(mystr.Length-6);
EDIT: too slow...
Upvotes: 16