Ask Question
28 March, 07:02

Complete the firstMiddleLast () function to return a new string with the first, middle, and last character from string. If string has an even number of characters, grab the middle two characters. It is safe to assume that no string passed in will be less than 3 characters.

+4
Answers (1)
  1. 28 March, 09:45
    0
    public static void main ()

    {

    String s = Console. ReadLine ();

    int len = s. length ();

    Char startletter = s[0];

    Char endletter = s[len-1];

    string midletter = '';

    if (len % 2 = =0)

    midletter = s[len/2] + s[ (len/2) + 1]

    else

    midletter = s[len/2];

    Console. WriteLine (startletter + midletter + endletter);

    }

    Here the logic is that, startletter is obtained using the index '0', the last letter is obtained by calculating the "length of the string" and subtract 1 to get the "last index" of the given string.

    Middle letter is calculated by first finding whether the given string length is "odd or even" and based on that index (es) are identified.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Complete the firstMiddleLast () function to return a new string with the first, middle, and last character from string. If string has an ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers