Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right Function in C#?

Tags:

c#

In VB there is a function called Right, which returns a string containing a specified number of characters from the right side of a string.

Is there a similar function in C# that does the same thing?

Thank you.

like image 275
Neo Avatar asked May 28 '13 02:05

Neo


People also ask

What is right in R?

right() counts from the right most position of a character string, for a specified number of characters, and returns the resulting substring. If the specified number of characters is more than the total length of the string, then the entire string will be returned.

What is string right?

A string containing a specified number of characters from the right side of a string.

What is right in C#?

Left, right, and mid string segments in C# In Visual Basic, for instance, Left() returns characters from the left side of a string. Right() does the same for string's right part. And Mid() returns a string segment that starts at a certain character index.

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

Simple approach should be taking Substring of an input string. var result = input. Substring(input. Length - 3);


3 Answers

Update: As mentioned in the comments below my previous answer fails in case the string is shorter than the requested length (the Right() in VB.net does not). So I've updated it a bit.

There is no similar method in C#, but you can add it with the following extension method which uses Substring() instead:

static class Extensions
{
    /// <summary>
    /// Get substring of specified number of characters on the right.
    /// </summary>
    public static string Right(this string value, int length)
    {
        if (String.IsNullOrEmpty(value)) return string.Empty;

        return value.Length <= length ? value : value.Substring(value.Length - length);
    }
}

The method provided is copied from DotNetPearls and you can get additional infos there.

like image 90
Chief Wiggum Avatar answered Oct 20 '22 15:10

Chief Wiggum


There is no built in function. You will have to do just a little work. Like this:

public static string Right(string original, int numberCharacters)
{
    return original.Substring(original.Length - numberCharacters);
}

That will return just like Right does in VB.

Hope this helps you! Code taken from: http://forums.asp.net/t/341166.aspx/1

like image 11
FrostyFire Avatar answered Oct 20 '22 15:10

FrostyFire


you can use all the visual basic specific functions in C#

like this :-

Microsoft.VisualBasic.Strings.Right(s, 10);

you will have to reference the Microsoft.VisualBasic Assembly as well.

like image 7
Keith Nicholas Avatar answered Oct 20 '22 13:10

Keith Nicholas