How to resize string in C++

3 Answers

0 votes
#include <iostream>
  
int main() {
    std::string s = "c++";
 
    std::cout << s << " : " << s.size() << "\n";
 
    s.resize(s.size() + 3, '+');     
     
    std::cout << s << " : " << s.size() << "\n";
}
  
  
  
/*
run:
  
c++ : 3
c+++++ : 6
  
*/

 



answered Dec 9, 2020 by avibootz
edited Apr 23, 2024 by avibootz
0 votes
#include <iostream>
   
int main() {
    std::string s = "c++";
  
    std::cout << s << " : " << s.size() << "\n";
  
    s.resize(s.size() + 5);     
      
    std::cout << s << " : " << s.size() << "\n";
     
    s[3] = ' '; s[4] = '1'; s[5] = '7';
     
    std::cout << s << " : " << s.size() << "\n";
}
   
   
   
/*
run:
   
c++ : 3
c++ : 8
c++ 17 : 8
   
*/

 



answered Dec 9, 2020 by avibootz
edited Apr 23, 2024 by avibootz
0 votes
#include <iostream>

using std::cout;
using std::endl;
using std::string;
 
int main()
{
    string s = "c c++ java php";
 
    cout << s.size() << endl;
 
    s.resize(30);
 
    cout << s.size() << endl;
}
 
 
/*
run:
 
14
30
 
*/

 



answered Apr 23, 2024 by avibootz

Related questions

4 answers 396 views
396 views asked Oct 23, 2025 by avibootz
2 answers 321 views
321 views asked Jul 22, 2020 by avibootz
1 answer 327 views
4 answers 837 views
2 answers 312 views
312 views asked May 4, 2018 by avibootz
1 answer 323 views
...