123

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?

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • You could use the source code for the VB.NET Right method. You'd need to convert to C# first: http://referencesource.microsoft.com/#Microsoft.VisualBasic/Strings.vb#0dbb15fffce19341 Convert to C# using http://converter.telerik.com/ – Darren Griffith May 13 '14 at 20:17
  • but the VB code relies on the c# Substring function in strings.sc – Our Man in Bananas Dec 11 '14 at 15:14
  • This is not really a very good way to do it, but if you're in a pinch, you can add a reference to Microsoft.VisualBasic.dll, and use the Right method. It is not an extension method. You have to use it like this: `string endOfString = Strings.Right(wholeString, 6);` – Alan McBee Jan 22 '15 at 03:50
  • 3
    Possible duplicate of [How to get last 4 character from a string in c#?](http://stackoverflow.com/questions/6413572/how-to-get-last-4-character-from-a-string-in-c) – drzaus Dec 14 '15 at 17:33

22 Answers22

174
string SubString = MyString.Substring(MyString.Length-6);
Vilx-
  • 104,512
  • 87
  • 279
  • 422
  • 39
    This aproach does not work correctly if the string is not as long as the number of characters required. – stevehipwell Nov 12 '09 at 13:59
  • 1
    Depending on what exactly the OP wants one might also throw regular expressions at this. If s?he only wants the number at the end of the string, that's definitely the most painless solution, especially when the number of digits may vary in some later software upgrade. – Joey Nov 12 '09 at 14:10
  • 2
    @Johannes Rössel - I'm a big fan of regular expressions (see my answers), but I'd never recomend them for a simple situation such as this. Any of the answers that use a function wrapper are better suited to code maintanance than a regular expression. An extension method (or standard function if .NET 2.0) is the best solution. – stevehipwell Nov 12 '09 at 14:57
  • @Stevo3000 - having a solution that throws if the string is the wrong length is a valid solution. Not the only solution, but still. – Marc L. May 19 '14 at 21:10
  • 3
    @James - to be just as pernickity, only the title mentioned "n letters". The actual question posed asked for "the rightmost six letters" :) – Chris Rogers Mar 05 '15 at 21:39
  • @ChrisRogers this is true... however, I think it's obvious that a general utility function is more useful than a strict "give me 6 chars" function. – James Dec 22 '17 at 03:31
  • The question I read was `How can I extract a substring which is composed of the rightmost six letters from another string? ... How can I do this?` From this I gather that the OP had problems with exactly this part - the substring extraction itself. My answer shows how to do this. If the OP has other requirements beyond that (which is likely, but not mentioned here), he/she can adapt this line into a larger solution as fits his/her needs. – Vilx- Dec 22 '17 at 08:11
73

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;
}
Jonathan S.
  • 5,837
  • 8
  • 44
  • 63
stevehipwell
  • 56,138
  • 6
  • 44
  • 61
43

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);
James
  • 80,725
  • 18
  • 167
  • 237
  • 20
    Then it would throw a NullReferenceException just like it would if you tried to use any method on a null string... – James Nov 13 '09 at 09:16
  • 1
    `str.Length - length` could be negative. Also the second parameter is optional. No need to pass the length. – iheartcsharp Dec 21 '17 at 20:02
  • 1
    @JMS10 it certainly could be but thats more the callers concern than mine. Also, yes fair point, you could use the override that just takes the single parameter here. – James Dec 22 '17 at 03:31
  • str?.Substring(str.Length - length, length); – Ludwo Jul 17 '19 at 12:35
27
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);

Jeff Crawford
  • 341
  • 4
  • 3
16

MSDN

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

EDIT: too slow...

RvdK
  • 19,580
  • 4
  • 64
  • 107
10

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.

Mahdi Tahsildari
  • 13,065
  • 14
  • 55
  • 94
  • 1
    Yea; let's just assume OP's text ALWAYS has white spaces; like in his _example_ :) – Christian Jan 15 '20 at 09:03
  • 1
    Hei Christian :) we all know more than a couple of lines of an answer. I just answered the question in brief, of course, there are a lot more things to consider in real code. – Mahdi Tahsildari Jan 15 '20 at 09:21
9

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;
chills42
  • 14,201
  • 3
  • 42
  • 77
  • -1 regular expressions are a little overkill for something like this, especially when there are already built in methods for doing it. – James Nov 13 '09 at 09:17
  • 1
    I'm not arguing for using this method if you really do only need the last 6, but if your goal is to extract a number (such as an id) that may change to 5 or 7 digits at some point in the future, this is a better way. – chills42 Nov 13 '09 at 13:24
  • 2
    Old answer, but +1 to support use of regular expressions. Especially since there are (still) no built-in methods in .NET's String implementation for doing this @James. Otherwise, this question may not have ever existed. – CrazyIvan1974 May 18 '17 at 01:59
  • @CrazyIvan1974 not sure why you've mentioned me in your comment – James May 18 '17 at 10:50
9

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.

Community
  • 1
  • 1
Aaron Thomas
  • 5,054
  • 8
  • 43
  • 89
6

Use this:

String text = "PER 343573";
String numbers = text;
if (text.Length > 6)
{
    numbers = text.Substring(text.Length - 6);
}
cjk
  • 45,739
  • 9
  • 81
  • 112
5

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;
Wade
  • 91
  • 3
  • Does this solution not reasonably meet the vague requirements? If not, please explain your down voting. – Wade Nov 13 '09 at 15:42
5
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"
Supawat Pusavanno
  • 2,968
  • 28
  • 21
4

Another solution that may not be mentioned

S.Substring(S.Length < 6 ? 0 : S.Length - 6)
FLICKER
  • 6,439
  • 4
  • 45
  • 75
3

Use this:

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

Brandao
  • 105
  • 1
  • 9
3

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));
Hossein
  • 1,640
  • 2
  • 26
  • 41
2

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);
        }
    }
Yves Schelpe
  • 3,343
  • 4
  • 36
  • 69
2

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);
}
2
//s - your string
//n - maximum number of right characters to take at the end of string
(new Regex("^.*?(.{1,n})$")).Replace(s,"$1")
vldmrrr
  • 748
  • 6
  • 8
  • Somebody flagged your post for deletion and [I saw it in a review queue](https://stackoverflow.com/review/low-quality-posts/18802695). I think your post was incorrectly flagged. [Code-only answers are not low-quality](https://meta.stackoverflow.com/a/358757/1364007). Does it attempt to answer the question? If not, flag. Is it technically incorrect? Downvote. – Wai Ha Lee Feb 12 '18 at 23:05
  • 1
    Code should be accompanied with a written explanation on how it fixes the issue in the OP. – Zze Feb 13 '18 at 00:01
  • 2
    Well, i thought written explanation in comments was sufficient, no? – vldmrrr Feb 13 '18 at 15:14
1

Just a thought:

public static string Right(this string @this, int length) {
    return @this.Substring(Math.Max(@this.Length - length, 0));
}
Hamid Sadeghian
  • 494
  • 1
  • 7
  • 11
0

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);
}
CJM
  • 11,908
  • 20
  • 77
  • 115
  • 2
    `Array.Reverse` takes an array, not a string, and `if (myString.length > 6)`. Syntax errors aside, why would this be the fastest method? Surely just using substring would be a better way, it wouldn't require all this copying of arrays. – 1800 INFORMATION Dec 19 '13 at 02:54
0

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;
    }
RitchieD
  • 1,831
  • 22
  • 21
0
using Microsoft.visualBasic;

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

output is "Word"

Steve Short
  • 85
  • 1
  • 12
0
            //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) : "";
zanfilip
  • 101
  • 1
  • 1