w3resource

C#: Exchange the first and last characters in a given string and return the new string


Exchange First and Last Characters

Write a C# Sharp program to exchange the first and last characters in a given string and return the new string.

Visual Presentation:

C# Sharp: Basic Algorithm Exercises - Exchange the first and last characters in a given  string and return the new 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)
        {
            // Calling the 'test' method with different strings and displaying the returned values
            Console.WriteLine(test("abcd"));  // Output: "dbca"
            Console.WriteLine(test("a"));     // Output: "a"
            Console.WriteLine(test("xy"));    // Output: "yx"
            Console.ReadLine();               // Keeping the console window open
        }

        // Method to perform a specific string transformation
        public static string test(string str)
        {
            // Checking if the length of the input string is greater than 1
            // If yes, the transformation is performed; otherwise, the input string is returned as is
            return str.Length > 1
                // Ternary operator used to rearrange characters based on certain positions
                ? str.Substring(str.Length - 1) + str.Substring(1, str.Length - 2) + str.Substring(0, 1)
                // Returns the input string itself if its length is 1 or 0
                : str;
        }
    }
}

Sample Output:

dbca
a
yx

Flowchart:

C# Sharp: Flowchart: Exchange the first and last characters in a given string and return the new string.

For more Practice: Solve these Related Problems:

  • Write a C# program to rotate a string left by one and swap the new first and last characters.
  • Write a C# program to swap the second and second-last characters of a string, if they exist.
  • Write a C# program to reverse a string if the first and last characters are the same.
  • Write a C# program to exchange the first three and last three characters of a string of at least 6 characters.

Go to:


PREV : Remove Character at Position.
NEXT : Four Copies of First Two 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.