Extract only right most n letters from a string

C#StringSubstring

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

string SubString = MyString.Substring(MyString.Length-6);

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

MSDN

String mystr = "PER 343573";
String number = mystr.Substring(mystr.Length-6);

EDIT: too slow...

Solution 6 - C#

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.

Solution 7 - C#

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;

Solution 8 - C#

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.

Solution 9 - C#

Use this:

String text = "PER 343573";
String numbers = text;
if (text.Length > 6)
{
    numbers = text.Substring(text.Length - 6);
}

Solution 10 - C#

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;

Solution 11 - C#

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"

Solution 12 - C#

Another solution that may not be mentioned

S.Substring(S.Length < 6 ? 0 : S.Length - 6)

Solution 13 - C#

Use this:

string mystr = "PER 343573"; int number = Convert.ToInt32(mystr.Replace("PER ",""));

Solution 14 - C#

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

Solution 15 - C#

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

Solution 16 - C#

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

Solution 17 - C#

//s - your string
//n - maximum number of right characters to take at the end of string
(new Regex("^.*?(.{1,n})$")).Replace(s,"$1")

Solution 18 - C#

Just a thought:

public static string Right(this string @this, int length) {
    return @this.Substring(Math.Max(@this.Length - length, 0));
}

Solution 19 - C#

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

Solution 20 - C#

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

Solution 21 - C#

using Microsoft.visualBasic;

 public class test{
  public void main(){
   string randomString = "Random Word";
   print (Strings.right(randomString,4));
  }
 }

output is "Word"

Solution 22 - C#

            //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) : "";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShyjuView Question on Stackoverflow
Solution 1 - C#Vilx-View Answer on Stackoverflow
Solution 2 - C#stevehipwellView Answer on Stackoverflow
Solution 3 - C#JamesView Answer on Stackoverflow
Solution 4 - C#Jeff CrawfordView Answer on Stackoverflow
Solution 5 - C#RvdKView Answer on Stackoverflow
Solution 6 - C#Mahdi TahsildariView Answer on Stackoverflow
Solution 7 - C#chills42View Answer on Stackoverflow
Solution 8 - C#Aaron ThomasView Answer on Stackoverflow
Solution 9 - C#cjkView Answer on Stackoverflow
Solution 10 - C#WadeView Answer on Stackoverflow
Solution 11 - C#Supawat PusavannoView Answer on Stackoverflow
Solution 12 - C#FLICKERView Answer on Stackoverflow
Solution 13 - C#BrandaoView Answer on Stackoverflow
Solution 14 - C#desmatiView Answer on Stackoverflow
Solution 15 - C#Yves SchelpeView Answer on Stackoverflow
Solution 16 - C#Tony_KiloPapaMikeGolfView Answer on Stackoverflow
Solution 17 - C#vldmrrrView Answer on Stackoverflow
Solution 18 - C#Hamid SadeghianView Answer on Stackoverflow
Solution 19 - C#user86157View Answer on Stackoverflow
Solution 20 - C#RitchieDView Answer on Stackoverflow
Solution 21 - C#Steve ShortView Answer on Stackoverflow
Solution 22 - C#zanfilipView Answer on Stackoverflow