我想检索给定奇数长度字符串的中间三个字符。例如。如果
string original = "India" // expected output - "ndi"
string original = "America" // expected output - "eri"
我尝试了以下代码,它按要求工作,但我想知道有没有更好的方法来做同样的事情?
public string GetMiddleString (string original)
{
string trimmed = string.Empty;
int midCharIndex = (original.Length / 2);
if ((original.Length) % 2 != 0)
{
trimmed = original.Substring (midCharIndex - 1, 3);
}
else
{
trimmed = original;
}
return trimmed;
}