Get the Middle Character – a programming exercise for the beginners series.

You are walking on a beach in Malibu, and you see an old oil lamp. You start rubbings it, with a strange light in your eyes, and then a message pops up in before you:
We are in desperate need and only you can help us. Please, oh mighty coder, write us a FUNCTION.”

A special function indeed:
We have many strings, and we need a tool that will helps us to find THE MIDDLE character in a given string.

If the words length is odd we need to find the one middle character.
If the words length is even we need to find the two middle characters.

Word: "Program"; Characters 7; Odd; So the middle one is 'g';
Word: "Nice"; Characters 4; Even; The middle two characters will be "ic"

For the solution of this programming exercise you can scroll down.

Have fun 🙂

The plan:

First we have to establish is the word length odd or even. And then, return the one or the two middle characters.

    public static string GetMiddle(string s)
        //Step 1
        if (s.Length%2==1)
            //Step 2
            return s[s.Length / 2].ToString();
            //Step 3
            return s[(s.Length / 2)-1].ToString() + s[(s.Length / 2)];

Step 1
To determine if the word is odd or even we are going to use the reminder % operator. The reminder operator (%) gives what remain after the division of the two items. Length%2 will divide Length with 2 and return the reminder. And if there is no remainder after the division the length is even, and if the reminder is 1 the length is odd.
To get the length of the string we are going to use the Length property that all string objects have.

Step 2
Now, if the word is odd we need to return the one middle character. In c#, we can directly get(read-only) a character from a string by treating it as an character array. Again, we are using Length and then divide it by two in order to get the middle position. This will give us a character. But the Function requires a string. So will use ToString() method, to convert it to one, and return the result.
I will do all that in one line of code. But it is ok to simplify it on several lines.

Step 3
If the word is even we need two characters. Again we are using this magical integer division(result from dividing two integers have also to be an integer) so many languages have.
In one line we get the two characters, add them together and return them as the result.