w3resource

C#: Create a new string from a given string with the first character added at the front and back


Add First Character to Front and Back

Write a C# program to create a string from a given string (length 1 or more) with the first character added at the front and back.

C# Sharp Exercises: Create a new string from a given string with the first character added at the front and back

Sample Solution:-

C# Sharp Code:

using System;
using System.Text;

// This is the beginning of the Exercise17 class
public class Exercise17 {
    // This is the main method where the program execution starts
    static void Main(string[] args)
    {
        string str; // Declaring a variable to store the input string

        // Prompting the user to input a string
        Console.Write("Input a string : ");
        str = Console.ReadLine(); // Reading the input string from the user

        // Checking if the input string has a length of at least 1 character
        if (str.Length >= 1)
        {
            var s = str.Substring(0, 1); // Extracting the first character of the string

            // Printing the string with the first character added at the beginning and end
            Console.WriteLine(s + str + s);
        }
    }
}

Sample Output:

Input a string : The quick brown fox jumps over the lazy dog.          
TThe quick brown fox jumps over the lazy dog.T

Flowchart:

Flowchart: C# Sharp Exercises - Create a new string from a given string with the first character added at the front and back

For more Practice: Solve these Related Problems:

  • Write a C# program that adds the second character to the front and back of a string if its length is even.
  • Write a C# program to add the last character to the beginning and middle of the string.
  • Write a C# program that appends the ASCII value of the first character to the end of the string.
  • Write a C# program to repeat the first character n times at the front and back, where n is its position in alphabet.

Go to:


PREV : Swap First and Last Characters.
NEXT : Check Positive and Negative Pair.

C# Sharp Code Editor:



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.