How to get the middle character from string in C++

2 Answers

0 votes
#include <iostream>

int main() {
    std::string s = "programming";

    int index = (int)(s.size() / 2);

    std::cout << s[index];
}


/*
run:
  
a
  
*/

 



answered Dec 2, 2020 by avibootz
0 votes
#include <iostream>
 
int main() {
    std::string s = "python";
 
    int len = s.size();
    int index = (int)(len / 2);
 
    if (len % 2 == 1) {
        std::cout << s[index];
    } else if (len % 2 == 0) {
        std::cout << s[index - 1] << "\n";
        std::cout << s[index] << "\n";
    }
}
 
 
 
/*
run:
   
t
h
   
*/

 



answered Dec 2, 2020 by avibootz
edited Mar 16, 2024 by avibootz

Related questions

2 answers 145 views
2 answers 176 views
1 answer 112 views
1 answer 109 views
1 answer 119 views
2 answers 130 views
2 answers 132 views
...