Getting middle three characters of an odd length string

asp.net, c#, c#-4.0, string

Solution

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.

Problem

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; } ```

Original source