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

查看:26
本文介绍了.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天全站免登陆