C#: Create a new string which contain the n copies of the first 3 characters of a given string
n Copies of First Three Characters
Write a C# Sharp program to create a string that is n (non-negative integer) copies of the first 3 characters of a given string. If the given string is shorter than 3, return n copies of the string.
Visual Presentation:

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("Python", 2));  // Output: PytPyt
            Console.WriteLine(test("Python", 3));  // Output: PytPytPyt
            Console.WriteLine(test("JS", 3));      // Output: JSJSJS
            Console.ReadLine();                    // Keeping the console window open
        }
        // Method to generate a string that repeats the first few characters 'n' times
        public static string test(string s, int n)
        {
            var result = string.Empty;   // Initialize an empty string to store the resulting string
            var frontOfString = 3;      // Define the number of characters to repeat
            // Check if the defined number of characters to repeat exceeds the length of the input string
            if (frontOfString > s.Length)
                frontOfString = s.Length;  // Adjust the number of characters to repeat to the length of the input string
            var front = s.Substring(0, frontOfString);  // Extract the specified number of characters from the beginning of the input string
            // Loop 'n' times to concatenate the extracted characters to the result string
            for (var i = 0; i < n; i++)
            {
                result += front;  // Concatenate the extracted characters 'n' times to the result string
            }
            return result;  // Return the resulting concatenated string
        }
    }
}
Sample Output:
PytPyt PytPytPyt JSJSJS
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C# program to generate a string consisting of n copies of the first 3 characters and the last 2 characters of a given string.
 - Write a C# program to generate n repetitions of the first three characters of a string, ignoring any whitespace characters.
 - Write a C# program to return n copies of the substring formed by the first vowel and its succeeding two characters from a given string.
 - Write a C# program to repeat the first 3 characters of a string n times and alternate them with dashes.
 
Go to:
PREV : n Copies of String.
NEXT : Count 'aa' in String.
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.
