C++ program to concatenate a string given number of times
Write a function which returns a new string which is made by concatenating a given string n number of times.
Examples:
Input : str = "geeks"
n = 3
Output : str = "geeksgeeksgeeks"
We concatenate "geeks" 3 times
Input : str = "for"
n = 2
Output : str = "forfor"
We concatenate "for" 2 times
Implementation:
CPP
#include <bits/stdc++.h>
#include <string>
using namespace std;
string repeat(string s, int n)
{
string s1 = s;
for ( int i=1; i<n;i++)
s += s1;
return s;
}
int main()
{
string s = "geeks" ;
int n = 3;
cout << repeat(s, n) << endl;;
return 0;
}
|
Java
class GFG {
static String repeat(String s, int n)
{
String s1 = s;
for ( int i = 1 ; i < n; i++)
s += s1;
return s;
}
public static void main(String[] args)
{
String s = "geeks" ;
int n = 3 ;
System.out.println(repeat(s, n));
}
}
|
Python3
def repeat(s, n):
s1 = s
for i in range ( 1 , n):
s + = s1
return s
s = "geeks"
n = 3
print (repeat(s, n))
|
C#
using System;
class GFG {
static String repeat(String s, int n)
{
String s1 = s;
for ( int i = 1; i < n; i++)
s += s1;
return s;
}
public static void Main()
{
String s = "geeks" ;
int n = 3;
Console.Write(repeat(s, n));
}
}
|
Javascript
<script>
function repeat(s, n)
{
let s1 = s;
for (let i = 1; i < n; i++)
s += s1;
return s;
}
let s = "geeks" ;
let n = 3;
document.write(repeat(s, n));
</script>
|
Time complexity: O(n) where n is number of times the string is repeated.
Auxiliary Space: O(n) for storing temporary string.
Last Updated :
16 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...