Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract only right most n letters from a string

People also ask

How do I extract the first few letters in R?

To get the first n characters from a string, we can use the built-in substr() function in R. The substr() function takes 3 arguments, the first one is a string, the second is start position, third is end position.

How do I get the last 3 characters of a string in R?

To get the last n characters from a string, we can use the stri_sub() function from a stringi package in R. The stri_sub() function takes 3 arguments, the first one is a string, second is start position, third is end position.

How do I get the right substring in C#?

To get the right part of a string we call the Substring() method on that particular string. We give that method two arguments. The first is the start index. To fetch the right part that index is the string's length minus the number of characters we want.


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

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

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

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