如何在C#中获取子字符串?

Nan*_* HE 49 c# string

我可以使用下面的函数获得前三个字符.

但是,如何通过函数获得最后五个字符()的输出Substring().或者将使用其他字符串函数?

static void Main()
{
    string input = "OneTwoThree";

    // Get first three characters
    string sub = input.Substring(0, 3);
    Console.WriteLine("Substring: {0}", sub); // Output One. 
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 69

如果您的输入字符串长度少于五个字符,那么您应该知道如果参数为负数string.Substring则会抛出一个字符.ArgumentOutOfRangeExceptionstartIndex

要解决此潜在问题,您可以使用以下代码:

string sub = input.Substring(Math.Max(0, input.Length - 5));
Run Code Online (Sandbox Code Playgroud)

或者更明确地说:

public static string Right(string input, int length)
{
    if (length >= input.Length)
    {
        return input;
    }
    else
    {
        return input.Substring(input.Length - length);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Nano HE:`Math.Max(int,int)`返回传入的两个数中的最大值.因此,在这种情况下,如果`input.Length`长度小于5个字符,则`Substring`有效地传递给`0`给你全部的"输入".否则,您将获得右侧5个字符的子字符串. (2认同)

ken*_*ytm 14

string sub = input.Substring(input.Length - 5);
Run Code Online (Sandbox Code Playgroud)


PMN*_*PMN 9

如果您可以使用扩展方法,无论字符串长度如何,这都将以安全的方式执行:

public static string Right(this string text, int maxLength)
{
    if (string.IsNullOrEmpty(text) || maxLength <= 0)
    {
        return string.Empty;
    }

    if (maxLength < text.Length)
    {
        return text.Substring(text.Length - maxLength);
    }

    return text;
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

string sub = input.Right(5);
Run Code Online (Sandbox Code Playgroud)

  • 我真的很讨厌这不是SubString开箱即用的方式.在一个小于LEN的字符串上调用Substring(0,LEN)是很常见的,我总是喜欢它只适用于那种情况,而不是抛出一个darned异常.我使用Math.Min解决方法,但对它不满意. (3认同)

Meh*_*hdi 9

static void Main()
    {
        string input = "OneTwoThree";

            //Get last 5 characters
        string sub = input.Substring(6);
        Console.WriteLine("Substring: {0}", sub); // Output Three. 
    }
Run Code Online (Sandbox Code Playgroud)

Substring(0,3)返回前3个字符的子字符串.//一

Substring(3,3)返回第二个3个字符的子字符串.//二

Substring(6)返回第一个6./3之后所有字符的子字符串