C# str.Substring(n,2)如何绕过ArgumentOutOfRangeException
问题:C# str.Substring(n,2)如何绕过ArgumentOutOfRangeException,c#,C#,问题: 给定字符串和索引,返回从给定索引开始的字符串长度2。 如果索引太大或太小,无法定义字符串长度2,请使用前2个字符。 字符串长度将至少为2。 输出: TakeTwoFromPosition("java", 0); // output "ja" TakeTwoFromPosition("java", 2); // output "va" TakeTwoFromPosition("java", 3); // output "ja" 解决方案: namespace TakeTw
给定字符串和索引,返回从给定索引开始的字符串长度2。
如果索引太大或太小,无法定义字符串长度2,请使用前2个字符。
字符串长度将至少为2。
输出:
TakeTwoFromPosition("java", 0); // output "ja"
TakeTwoFromPosition("java", 2); // output "va"
TakeTwoFromPosition("java", 3); // output "ja"
解决方案:
namespace TakeTwoFromPosition
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(TakeTwoFromPosition("Hello",1));
Console.WriteLine(TakeTwoFromPosition("java", 3));
Console.ReadLine();
}
public static string TakeTwoFromPosition(string str, int n)
{
// ArgumentOutOfRangeException bug = new ArgumentOutOfRangeException(str.Substring(n, 2));
if (str.Substring(n, 2).Length + str.Substring(0, n).Length <= str.Length && str.Length >= 2)
{
return str.Substring(n, 2);
}
else if (str.Substring(n, 2).Length + str.Substring(0, n).Length > str.Length && str.Length >= 2)
{
return str.Substring(0, 2);
}
return str.Substring(0,2);
}
}
}
名称空间采用两个fromPosition
{
班级计划
{
静态void Main(字符串[]参数)
{
Console.WriteLine(从position(“Hello”,1)取两个);
Console.WriteLine(taketworfromposition(“java”,3));
Console.ReadLine();
}
公共静态字符串TakeTwoFromPosition(字符串str,int n)
{
//ArgumentOutOfRangeException错误=新ArgumentOutOfRangeException(str.Substring(n,2));
if(str.Substring(n,2).Length+str.Substring(0,n).Length=2)
{
返回str.Substring(n,2);
}
else if(str.Substring(n,2).Length+str.Substring(0,n).Length>str.Length&&str.Length>=2)
{
返回str.Substring(0,2);
}
返回str.Substring(0,2);
}
}
}
直到现在我才明白,但在索引太大或太小而无法定义长度为2的字符串的部分,我需要帮助。因此,如果
str.Substring(n,2)
没有引用字符串中的位置如何在调用错误之前返回str.Substring(0,2),如果
它在范围内只要运行
if
语句即可。您可以使用条件语句来检查它是否在范围内
if(n + 2 > str.Length)
return str.Substring(0,2);
else
return str.Substring(n,2);
您可能还需要检查str的长度是否至少为2个字符。我想这应该满足您的要求:
public static string TakeTwoFromPosition(string str, int n)
{
if (str.Length <= n + 2)
{
return str.Substring(n, 2);
}
return str.Substring(0, 2);
}
公共静态字符串TakeTwoFromPosition(字符串str,int n)
{
如果(str.Length您应该事先检查所提供字符串的长度,您不认为吗?您正在运行直接代码,而没有检查字符串的长度是否允许它。如果索引太大或太小而无法定义字符串长度,那么考虑到字符串长度至少为2,索引怎么可能太小