string类的扩充
public static string Substr(string input, int start) {
if (input == null || Math.Abs(start) > input.Length) {
return null;
} else if (start < 0) {
return input.Substring(Math.Max(0, input.Length + start));
} else {
return input.Substring(start);
}
}
public static string Substr(string input, int start, int len) {
if (input == null || Math.Abs(start) > input.Length || len < 0) {
return null;
} else if (start < 0) {
return input.Substring(Math.Max(0, input.Length + start), Math.Min(Math.Abs(start), len));
} else {
return input.Substring(start, Math.Min(input.Length - start, len));
}
}
例子:
string x = "12345";
string y = null;
y = Substr(x, 0); // y 值为 "12345"
y = Substr(x, -1); // y 值为 "1234"
y = Substr(x, 100); // y 值为 null
y = Substr(x, 0, 2); // y 值为 "12"
y = Substr(x, 0, -1); // y 值为 null; (这里和 PHP 不同, PHP 会截取负长度, 个人感觉该方式逻辑比较混乱)
y = Substr(x, -4, 2); // y 值为 "23"