.NET相当于旧的vb left(string,length)函数


69

作为非.NET程序员,我正在寻找与旧版Visual Basic函数等效的.NET left(string, length)。这很懒,因为它适用于任何长度的字符串。不出所料,left("foobar", 3) = "foo"最有帮助的是left("f", 3) = "f"

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


@Noldorin-哇,谢谢您的VB.NET扩展!我的第一次接触,尽管花了我几秒钟的时间在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#扩展


很高兴为您介绍了他们。:)它们是VB.NET和C#的非常有用的功能(只要您知道如何正确使用它们),并且您会发现它们一直在派上用场。顺便说一下,不确定您是否意识到,但是Math.Min函数是BCL的一部分,因此您也可以在C#中使用它。
诺多林

@Nolderin-非常整洁,经过编辑以反映Math.Min注释。谢谢!
乔什

1
作为一个脚注,返回新字符串(str.Take(length).ToArray()); 也可以。我想使用子字符串可能更快。
肖恩

3
也可以使用return str.Length > length ? str.Remove(length) : str;
Jeppe Stig Nielsen,

另一种方式:return string.Concat(str.Take(length));
Rufus L

Answers:


56

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

<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

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

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

只是在输入扩展方法的示例。
j0tt

1
@Oded:它们肯定在VB.NET 9中起作用。您需要指定Extension属性,该属性与C#的方法完全不同。参见msdn.microsoft.com/en-us/library/bb384936.aspx
Noldorin,2009年

最初的问题没有说明扩展方法。似乎要切线了。
andleer

4
@安德鲁·罗宾逊:我想不是。仅仅因为他没有提及它,并不意味着它不是有效的答案。实际上,因为他没有提及它,所以我怀疑它可能对他感兴趣。添加额外的信息可能会有所帮助。:)
Noldorin

36

另一行选项将如下所示:

myString.Substring(0, Math.Min(length, myString.Length))

其中myString是您要使用的字符串。


这是我想到的第一个解决方案。我认为必须有一种更轻松/内置的方式。但是,有没有...
了Krisztián巴拉

我期待这个答案。谢了哥们。
哈里2014年

32

添加到Microsoft.VisualBasic程序库的引用,你可以使用Strings.Left正是同样的方法。


1
更简单的解决方案-重新发明轮子的目的是什么?
Billious 2011年

如果我想完全摆脱.Net应用程序中的VB引用怎么办?
哈里2014年

4
就像找不到汤匙时用叉子搅拌汤一样。
了Krisztián巴拉

4
@ JennyO'Reilly虽然您的隐喻是丰富多彩的,但却被误用了。OP要求提供VB功能,而这正是他所要求的。
FistOfFury 2014年

它只是添加了另一个函数库以节省您的时间。如果您觉得“ VB”感觉更好,可以遮住眼睛。
史蒂夫(Steve)

13

不要忘记null情况:

public static string Left(this string str, int count)
{
    if (string.IsNullOrEmpty(str) || count < 1)
        return string.Empty;
    else
        return str.Substring(0,Math.Min(count, str.Length));
}

6

采用:

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
}

它应该不会出错,以空字符串返回null,并返回修剪或基值。像“ testx” .Left(4)或str.Right(12);一样使用它。


5

您可以自己制作:

private string left(string inString, int inInt)
{
    if (inInt > inString.Length)
        inInt = inString.Length;
    return inString.Substring(0, inInt);
}

我的是C#,您必须为Visual Basic对其进行更改。


2

您可以将对子字符串的调用包装到一个新函数中,该函数将按照其他答案(正确的方法)中的建议测试其长度,或者使用Microsoft.VisualBasic命名空间并直接使用left(通常被认为是错误的方法!)


您不应该使用Try ... Catch捕获可以很容易地事先检查的内容。
加法

1
为什么使用VisualBasic命名空间被认为是“错误的方式”?这就是为什么将其包括在内。它是VB的一部分。
克里斯·邓纳威

2

另一种技术是通过添加Left()方法来扩展字符串对象。

这是有关此技术的原始文章:

http://msdn.microsoft.com/en-us/library/bb384936.aspx

这是我的实现(在VB中):

Module StringExtensions

    <Extension()>
    Public Function Left(ByVal aString As String, Length As Integer)
        Return aString.Substring(0, Math.Min(aString.Length, Length))
    End Function

End Module

然后将其放在要使用扩展名的任何文件的顶部:

Imports MyProjectName.StringExtensions

像这样使用它:

MyVar = MyString.Left(30)

1

我喜欢做这样的事情:

string s = "hello how are you";
s = s.PadRight(30).Substring(0,30).Trim(); //"hello how are you"
s = s.PadRight(3).Substring(0,3).Trim(); //"hel"

但是,如果您想要尾随或开头的空格,那么您就不走运了。

我真的很喜欢使用Math.Min,这似乎是一个更好的解决方案。


0

如果要避免使用扩展方法并防止长度不足的错误,请尝试此操作

string partial_string = text.Substring(0, Math.Min(15, text.Length)) 
// example of 15 character max

0

只是在一个非常特殊的情况下:

如果您正在这样做,则将使用一些部分字符串来检查数据,例如:

if(Strings.Left(str, 1)=="*") ...;

然后,您还可以使用C#实例方法,例如StartsWithEndsWith执行这些任务。

if(str.StartsWith("*"))...;

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.