Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting middle three characters of an odd length string

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;
}
like image 356
RahulD Avatar asked Jul 16 '13 19:07

RahulD


2 Answers

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.

like image 146
Jonesopolis Avatar answered Oct 18 '22 05:10

Jonesopolis


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.

like image 32
Harrison Lambeth Avatar answered Oct 18 '22 05:10

Harrison Lambeth