w3resource

C# Sharp Basic Algorithm Exercises: Create a new string taking the first character from a given string and the last character from another given string


C# Sharp Basic Algorithm: Exercise-77 with Solution

Write a C# Sharp program to create a new string taking the first character from a given string and the last character from another given string. If the length of any given string is 0, use '#' as its  missing character.

Pictorial Presentation:

C# Sharp: Basic Algorithm Exercises - Create a new string taking the first character from a given string and the last character from another given string.

Sample Solution:-

C# Sharp Code:

using System;

namespace exercises
{
   class Program
    {       
        static void Main(string[] args)
        {
            Console.WriteLine(test("Hello", "Hi"));
            Console.WriteLine(test("Python", "PHP"));
            Console.WriteLine(test("JS", "JS"));
            Console.WriteLine(test("Csharp", ""));
            Console.ReadLine();
        }

 public static string test(string s1, string s2)
        {
            string lastChars = String.Empty;

            if (s1.Length > 0)
            {
                lastChars += s1.Substring(0, 1);
            }
            else
            {
                lastChars += "#";
            }

            if (s2.Length > 0)
            {
                lastChars += s2.Substring(s2.Length - 1);
            }
            else
            {
                lastChars += "#";
            }

            return lastChars;
        }
   }
}

Sample Output:

Hi
PP
JS
C#

Flowchart:

C# Sharp: Flowchart: Create a new string taking the first character from a given string and the last character from another given string.

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 of length 2, using first two characters of a given string. If the given string length is less than 2 use '#' as missing characters.
Next: Write a C# Sharp program to combine two given strings. If there are any double character in new string then omit one character.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.