I want to retrieve the middle three characters of a given odd length string. Eg. if
string original = "India" // expected output - "ndi"
string original = "America" // expected output - "eri"
I tried the following code and it works as per requirement but I was wondering is there any better way for doing the same?
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;
}
instead of the if you could use a ternary operator
return (!String.IsNullOrEmpty(original)
&& original.Length % 2 != 0
&& original.Length >= 3)
? original.Substring((original.Length / 2) - 1, 3)
: original;
which would be the only code inside the method needed. Added the && original.Length >= 3
to prevent an error.
Here's what I came up with. Not that it really changes much to your code
public string GetMiddleString(string original)
{
if (original.Length % 2 != 0 && original.Length >= 3)
return original.Substring(original.Length / 2 - 1, 3);
return original;
}
I'd make sure to check the length of the string so you don't get any exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With