How to get the middle character from string in C#

2 Answers

0 votes
using System;

class Program
{
    static void Main() {
        string s = "programming";
          
        int index = s.Length / 2;

        Console.Write(s[index]);
    }
}



/*
run:

a

*/

 



answered Dec 2, 2020 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        string s = "python";
          
        int len = s.Length;
        int index = len / 2;

        if (len % 2 == 1) {
             Console.Write(s[index]);
        } else if (len % 2 == 0) {
             Console.Write(s[index - 1]);
             Console.Write(s[index]);
        }
    }
}



/*
run:

th

*/

 



answered Dec 2, 2020 by avibootz

Related questions

1 answer 206 views
1 answer 163 views
1 answer 166 views
1 answer 208 views
1 answer 204 views
1 answer 214 views
...