How to concatenate (repeat) a string N times in C++

3 Answers

0 votes
#include <iostream>

void repeatNtimes(std::string &s, int n) {
   std::string tmp = s;
   for (int i = 1; i < n; i++)
      s += tmp; 
}

int main() {
   std::string s = "c++";
   
   int n = 4;
   
   repeatNtimes(s, n);
   
   std::cout << s;
   
   return 0;
}



/*
run:

c++c++c++c++

*/

 



answered Jun 29, 2020 by avibootz
0 votes
#include <iostream>
  
std::string repeatNtimes(std::string s, int n) {
    std::string tmp = s;
    for (int i = 1; i < n; i++)
        s += tmp; 
    return s;
}
  
int main() {
    std::string s = "c++";
     
    int n = 4;
     
    s = repeatNtimes(s, n);
     
    std::cout << s;
     
    return 0;
}
  
  
  
/*
run:
  
c++c++c++c++
  
*/

 



answered Jun 29, 2020 by avibootz
0 votes
#include <iostream>
  
std::string repeatNtimes(std::string s, int n) {
    std::string tmp = s;
    for (int i = 1; i < n; i++)
        s += tmp; 
    return s;
}
  
int main() {
    std::string s = "c++";
     
    int n = 4;
     
    s = repeatNtimes(repeatNtimes(s, n), n);
     
    std::cout << s;
     
    return 0;
}
  
  
  
/*
run:
  
c++c++c++c++c++c++c++c++c++c++c++c++c++c++c++c++
  
*/

 



answered Jun 29, 2020 by avibootz

Related questions

1 answer 200 views
1 answer 80 views
80 views asked Dec 23, 2024 by avibootz
1 answer 195 views
1 answer 186 views
186 views asked Feb 1, 2022 by avibootz
3 answers 261 views
1 answer 103 views
1 answer 89 views
89 views asked Dec 23, 2024 by avibootz
...