source

.NET은 이전 vb left(문자열, 길이) 함수와 동일합니다.

ittop 2023. 5. 12. 22:41
반응형

.NET은 이전 vb left(문자열, 길이) 함수와 동일합니다.

비전문가로서.NET 프로그래머를 찾고 있습니다.이전 Visual Basic 기능에 해당하는 NETleft(string, length)그것은 어떤 길이의 끈에서도 작동한다는 점에서 게을렀습니다.역시.left("foobar", 3) = "foo"한편, 가장 도움이 되는 것은,left("f", 3) = "f".

.NET에서string.Substring(index, length)모든 항목에 대한 예외를 범위 밖으로 던집니다.자바에서는 항상 Apache-Commons 언어를 사용했습니다.StringUtils 편리합니다.Google에서는 문자열 함수를 검색하는 데 그다지 큰 도움이 되지 않습니다.


@놀도린 - 와우, 당신의 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# 확장도 참조하십시오.

여기 그 일을 할 수 있는 확장 방법이 있습니다.

<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 구문, 즉.

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

또 다른 한 줄 옵션은 다음과 같습니다.

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

여기서 myString은 작업하려는 문자열입니다.

Microsoft에 참조를 추가합니다.Visual Basic 라이브러리에서 문자열을 사용할 수 있습니다.정확히 같은 방법인 왼쪽.

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

사용:

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"처럼 사용합니다.왼쪽(4) 또는 세로.오른쪽(12);

직접 만들 수 있습니다.

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

제 것은 C#에 있는데 Visual Basic으로 변경하셔야 합니다.

다른 답변에 제시된 대로 통화 길이를 테스트하는 새 함수로 통화를 하위 문자열로 감쌀 수 있습니다(올바른 방법). 또는 Microsoft를 사용할 수 있습니다.VisualBasic 네임스페이스 및 왼쪽에서 직접 사용(일반적으로 잘못된 방법으로 간주됨)

저는 다음과 같은 일을 하는 것을 좋아합니다.

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"

하지만, 만약 당신이 뒤에 오는 공간이나 시작 공간을 원한다면 당신은 운이 없습니다.

저는 수학을 정말 좋아합니다.민씨, 그게 더 나은 해결책인 것 같습니다.

또 다른 방법은 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)

확장 방법을 사용하지 않고 길이 미만 오류를 방지하려면 다음을 시도하십시오.

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

아주 특별한 경우:

왼쪽으로 이 작업을 수행하는 경우 다음과 같은 일부 문자열을 사용하여 데이터를 확인합니다.

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

C#메소드를 . 를 들어 C# 인스턴스 메소드를 사용할 수도 있습니다.StartsWith그리고.EndsWith이 작업을 수행할 수 있습니다.

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

언급URL : https://stackoverflow.com/questions/844059/net-equivalent-of-the-old-vb-leftstring-length-function

반응형