C ++程序连接字符串给定次数
编写一个函数,该函数返回一个新字符串,该字符串由给定字符串连接 n 次而成。
例子:
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
CPP
// C++ program to concatenate given string
// n number of times
#include
#include
using namespace std;
// Function which return string by concatenating it.
string repeat(string s, int n)
{
// Copying given string to temporary string.
string s1 = s;
for (int i=1; i
Java
// Java program to concatenate given
// string n number of times
class GFG {
// Function which return string by
// concatenating it.
static String repeat(String s, int n)
{
// Copying given string to
// temporary string.
String s1 = s;
for (int i = 1; i < n; i++)
// Concatenating strings
s += s1;
return s;
}
// Driver code
public static void main(String[] args)
{
String s = "geeks";
int n = 3;
System.out.println(repeat(s, n));
}
}
// This code is contributed by Smitha
Python3
# Python 3 program to concatenate
# given string n number of times
# Function which return string by
# concatenating it.
def repeat(s, n):
# Copying given string to
# temporary string.
s1 = s
for i in range(1, n):
# Concatenating strings
s += s1
return s
# Driver code
s = "geeks"
n = 3
print(repeat(s, n))
# This code is contributed
# by Smitha
C#
// C# program to concatenate given
// string n number of times
using System;
class GFG {
// Function which return string
// by concatenating it.
static String repeat(String s, int n)
{
// Copying given string to
// temporary string.
String s1 = s;
for (int i = 1; i < n; i++)
// Concatenating strings
s += s1;
return s;
}
// Driver code
public static void Main()
{
String s = "geeks";
int n = 3;
Console.Write(repeat(s, n));
}
}
// This code is contributed by Smitha
Javascript
输出:
geeksgeeksgeeks