How to How to remove the two middle characters from a string in C++

2 Answers

0 votes
#include <iostream>
 
void remove2CharsAt(std::string &s, int pos) {
    s = s.substr(0, pos - 1) + s.substr(pos + 1);
}
  
int main()
{
    std::string s1 = "abcde";
    remove2CharsAt(s1, s1.length() / 2);
    std::cout << s1 << "\n";
     
    std::string s2 = "abcdef";
    remove2CharsAt(s2, s2.length() / 2);
    std::cout << s2 << "\n";
}
 
 
 
/*
run:

ade
abef

*/

 



answered Jun 12, 2024 by avibootz
0 votes
#include <iostream>
 
void remove2MiddleCharacters(std::string& str) {
    size_t middlePos = str.length() / 2;
    
    str.erase(middlePos - 1, 2); 
}
  
int main()
{
    std::string s1 = "abcde";
    remove2MiddleCharacters(s1);
    std::cout << s1 << "\n";
     
    std::string s2 = "abcdef";
    remove2MiddleCharacters(s2);
    std::cout << s2 << "\n";
}
 
 
 
/*
run:

ade
abef

*/

 



answered Jun 12, 2024 by avibootz

Related questions

1 answer 185 views
1 answer 182 views
2 answers 285 views
1 answer 201 views
...