.NET等效于旧的vb left(string,length)函数 [英] .NET equivalent of the old vb left(string, length) function

查看:143
本文介绍了.NET等效于旧的vb left(string,length)函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为非.NET程序员,我正在寻找与旧的Visual Basic函数left(string, length)等效的.NET.这很懒,因为它适用于任何长度的字符串.正如预期的那样,left("foobar", 3) = "foo"而最有用的是left("f", 3) = "f".

As a non-.NET programmer I'm looking for the .NET equivalent of the old Visual Basic function left(string, length). It was lazy in that it worked for any length string. As expected, left("foobar", 3) = "foo" while, most helpfully, left("f", 3) = "f".

在.NET中,string.Substring(index, length)会为超出范围的所有内容抛出异常.在Java中,我总是很方便地使用Apache-Commons lang.StringUtils.在Google中,我对字符串功能的搜索并不遥远.

In .NET string.Substring(index, length) throws exceptions for everything out of range. In Java I always had the Apache-Commons lang.StringUtils handy. In Google I don't get very far searching for string functions.

@Noldorin -哇,谢谢您的VB.NET扩展!我的初次见面,尽管花了我几秒钟的时间在C#中执行相同的操作:

@Noldorin - Wow, thank you for your VB.NET extensions! My first encounter, although it took me several seconds to do the same in C#:

public static class Utils
{
    public static string Left(this string str, int length)
    {
        return str.Substring(0, Math.Min(length, str.Length));
    }
}

请注意静态类和方法以及this关键字.是的,它们的调用就像"foobar".Left(3)一样简单.另请参见 MSDN上的C#扩展.

Note the static class and method as well as the this keyword. Yes, they are as simple to invoke as "foobar".Left(3). See also C# extensions on MSDN.

推荐答案

这是可以完成这项工作的扩展方法.

Here's an extension method that will do the job.

<System.Runtime.CompilerServices.Extension()> _
Public Function Left(ByVal str As String, ByVal length As Integer) As String
    Return str.Substring(0, Math.Min(str.Length, length))
End Function

这意味着您可以像使用旧的VB Left函数(即Left("foobar", 3))一样使用它,也可以使用新的VB.NET语法,即

This means you can use it just like the old VB Left function (i.e. Left("foobar", 3) ) or using the newer VB.NET syntax, i.e.

Dim foo = "f".Left(3) ' foo = "f"
Dim bar = "bar123".Left(3) ' bar = "bar"

这篇关于.NET等效于旧的vb left(string,length)函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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