w3resource

C#: Create a new string with the last char added at the front and back of a given string of length 1 or more


C# Sharp Basic Algorithm: Exercise-9 with Solution

Write a C# Sharp program to create a string with the last char added at the front and back of a given string of length 1 or more.

Visual Presentation:

C# Sharp: Basic Algorithm Exercises - Create a new string with the last char added at the front and back of a given string of length 1 or more.

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)
        {
            // Calling the 'test' method with different strings and displaying the returned values
            Console.WriteLine(test("Red"));   // Output: "dRedd"
            Console.WriteLine(test("Green")); // Output: "nGreenn"
            Console.WriteLine(test("1"));     // Output: "11"
            Console.ReadLine();                // Keeping the console window open
        }

        // Method to perform a specific string transformation
        public static string test(string str)
        {
            // Extracts the last character of the input string
            var s = str.Substring(str.Length - 1);

            // Concatenates the last character, the input string, and the last character again
            return s + str + s;
        }
    }
}

Sample Output:

dRedd
nGreenn
111

Flowchart:

C# Sharp: Flowchart: Create a new string with the last char added at the front and back of a given string of length 1 or more

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# Sharp program to create a new string which is 4 copies of the 2 front characters of a given string.If the given string length is less than 2 return the original string.
Next: Write a C# Sharp program to check if a given positive number is a multiple of 3 or a multiple of 7.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/csharp-exercises/basic-algo/csharp-basic-algorithm-exercises-9.php