在C#中正确的功能? [英] Right Function in C#?

查看:57
本文介绍了在C#中正确的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VB中,有一个名为Right的函数,该函数从字符串的右侧返回包含指定数目的字符的字符串.

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.

C#中是否有类似的功能可以完成相同的工作?

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

谢谢.

推荐答案

更新:如下面的注释所述,如果字符串短于请求的长度( Right()不会).因此,我对其进行了一些更新.

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.

C#中没有类似的方法,但是您可以使用以下扩展方法添加它,该扩展方法改为使用 Substring():

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

提供的方法是从 DotNetPearls 复制而来的,您可以在此处获取其他信息.

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

这篇关于在C#中正确的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆