How to get the middle character of a word programmatically?

Get the middle character using C#. (this was not generated by ChatGPT or any other AI)

How to get the middle character of a word programmatically?
Photo by Markus Spiske / Unsplash

Here's the exercise on CodeWars.

You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.

Examples:

Kata.getMiddle("test") should return "es"

Kata.getMiddle("testing") should return "t"

Kata.getMiddle("middle") should return "dd"

Kata.getMiddle("A") should return "A"

This exercise can be tricky if you don't know how to get the middle character for a string.

  • First, I return the string if there's only 1 character
  • if the word is of even length, I use get the substring as asked in the exercise instructions
  • note: I divide the length by 2 and this shall return the highest value since it's an integer
using System;

public class Kata
{
  public static string GetMiddle(string s)
  {
    var length = s.Length;

    if (length == 1)
    {
      return s;
    }
    
    if (length % 2 == 0) // even
    {
      var divide = length / 2;
      return s.Substring(divide - 1, 2);
    }
    else  // odd
    {
      return s[s.Length / 2].ToString();
    }
  }
}
Codes