Substring 在长度不足时如何安全截取后 N 个字符
使用 math.max(0, length - n) 计算起始索引,再调用 substring。当字符串长度小于 n 时,起始索引为 0,返回整个字符串;否则返回最后 n 个字符。

using System;
class Program
{
static void Main()
{
string input = "Hello";
int n = 3;
// 计算起始位置:如果长度小于n,则从0开始
int startIndex = Math.Max(0, input.Length - n);
// 截取子串
string result = input.Substring(startIndex);
Console.WriteLine(result); // 输出: llo
// 测试长度不足的情况
string shortInput = "Hi";
int startShort = Math.Max(0, shortInput.Length - n);
string resultShort = shortInput.Substring(startShort);
Console.WriteLine(resultShort); // 输出: Hi
}
}
如何处理空字符串或 null 输入
在截取前检查输入是否为 null 或空,避免抛出异常。若输入为空,直接返回空字符串或默认值。

using System;
class Program
{
static void Main()
{
string input = null;
int n = 3;
// 处理 null 或空字符串
if (string.IsNullOrEmpty(input))
{
Console.WriteLine(string.Empty); // 输出: (空)
return;
}
int startIndex = Math.Max(0, input.Length - n);
string result = input.Substring(startIndex);
Console.WriteLine(result);
}
}
基于程序中某个输入、条件或结果的具体问题
当输入字符串长度恰好等于 N 时,起始索引为 0,返回整个字符串。这是正常行为,无需特殊处理。











