如何获得在C#中的子? [英] How to get the substring in C#?

查看:98
本文介绍了如何获得在C#中的子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以得到一个具有如下功能的前三个字符。

但是,我怎么能得到最后五个字符的输出()与子串()功能。或其他字符串函数会被使用?

感谢您。

 静态无效的主要()
        {
            字符串输入=OneTwoThree;            //获取前三个字符
            串子= input.Substring(0,3);
            Console.WriteLine(子字符串:{0},分); //输出一个。
        }


解决方案

如果您输入的字符串可以少于五个字符长,那么你应该知道的 string.Substring 将抛出一个 ArgumentOutOfRangeException 如果的startIndex 参数为负。

要解决,你可以使用下面的code这个潜在的问题:

 串子= input.Substring(Math.Max​​(0,input.Length  -  5));

或者更明确的:

 公共静态字符串右(字符串输入,INT长度)
{
    如果(长度GT; = input.Length)
    {
        返回输入;
    }
    其他
    {
        返回input.Substring(input.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 Substring() function. Or other string function will be used?

Thank you.

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#中的子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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