如何在C#中使用Substring()获取字符串的最后五个字符? [英] How to get the last five characters of a string using Substring() in C#?

查看:72
本文介绍了如何在C#中使用Substring()获取字符串的最后五个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



但是,如何使用 Substring()功能?还是必须使用另一个字符串函数?

  static void Main()
{
字符串输入=一个二三

//获取前三个字符
string sub = input.Substring(0,3);
Console.WriteLine( Substring:{0},sub); //输出一。
}


解决方案

如果您输入的字符串可能是少于五个字符,那么您应该意识到 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);
    }
}

这篇关于如何在C#中使用Substring()获取字符串的最后五个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆