w3resource

C#: Create a new string which is n copies of a given string


n Copies of String

Write a C# Sharp program to create a string which is n (non-negative integer) copies of a given string.

Visual Presentation:

C# Sharp: Basic Algorithm Exercises - Create a new string which is n (non-negative integer ) copies of a given string.

Sample Solution:-

C# Sharp Code:

using System;

// Namespace declaration
namespace exercises
{
    // Class declaration
    class Program
    {
        // Main method - entry point of the program
        static void Main(string[] args)
        {
            // Displaying the output of the 'test' method with different string inputs and integers
            Console.WriteLine(test("JS", 2));  // Output: JSJS
            Console.WriteLine(test("JS", 3));  // Output: JSJSJS
            Console.WriteLine(test("JS", 1));  // Output: JS
            Console.ReadLine();                // Keeping the console window open
        }

        // Method to concatenate a string 's' 'n' times
        public static string test(string s, int n)
        {
            string result = String.Empty;  // Initialize an empty string to store the result

            // Loop 'n' times to concatenate the input string 's'
            for (int i = 0; i < n; i++)
            {
                result += s;  // Concatenate the input string to the result string 'n' times
            }

            return result;  // Return the concatenated string
        }
    }
}

Sample Output:

JSJS
JSJSJS
JS

Flowchart:

C# Sharp: Flowchart: Create a new string which is n (non-negative integer ) copies of a given string.

For more Practice: Solve these Related Problems:

  • Write a C# program to create n copies of the first two characters of a given string. If the string is shorter than two characters, copy it entirely.
  • Write a C# program to create a string that alternates the original and its reverse for n times.
  • Write a C# program that repeats the string n times but inserts a hyphen between each copy.
  • Write a C# program that generates n copies of the original string but with alternating casing (upper, lower, upper...).

Go to:


PREV : Uppercase Last Three Characters.
NEXT : n Copies of First Three Characters.

C# Sharp Code Editor:



Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.