且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中使用Substring()获取字符串的最后五个字符?

更新时间:2023-02-04 23:18:17

如果您输入的字符串可能是少于五个字符,那么您应该意识到 string。如果 startIndex 参数为负,则子字符串 将引发 ArgumentOutOfRangeException 。 / p>

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

 字符串sub = input.Substring(Math.Max(0,input.Length-5)); 

或更明确地说:

 公共静态字符串Right(字符串输入,整数长度)
{
if(length> = input.Length)
{
return input;
}
else
{
return input.Substring(input.Length-length);
}
}


I can get the first three characters with the function below.

However, how can I get the output of the last five characters ("Three") with the Substring() function? Or will another string function have to be used?

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

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

If your input string could be less than five characters long then you should be aware that string.Substring will throw an ArgumentOutOfRangeException if the startIndex argument is negative.

To solve this potential problem you can use the following code:

string sub = input.Substring(Math.Max(0, input.Length - 5));

Or more explicitly:

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