w3resource

C#: Get a new string of two characters from a given string


Extract 'PH' from String

Write a C# program to get a string of two characters from a given string. The first and second characters of the given string must be "P" and "H", so PHP will be "PH".

C# Sharp Exercises: Get a new string of two characters from a given string

Sample Solution:-

C# Sharp Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Exercise38 {
    static void Main(string[] args) {
        // Define a string variable 'str1' and assign it the value "PHP Tutorial"
        string str1 = "PHP Tutorial";

        // Initialize an empty string variable 'result' to store the concatenated characters
        var result = "";

        // Check if the length of 'str1' is greater than or equal to 1 and if the first character is 'P'
        if (str1.Length >= 1 && str1[0] == 'P')
            // If true, append the first character 'P' to the 'result' string
            result += str1[0];

        // Check if the length of 'str1' is greater than or equal to 2 and if the second character is 'H'
        if (str1.Length >= 2 && str1[1] == 'H')
            // If true, append the second character 'H' to the 'result' string
            result += str1[1];

        // Print the final concatenated string stored in the 'result' variable
        Console.WriteLine(result);
    }
}

Sample Output:

PH

Flowchart:

Flowchart: C# Sharp Exercises - Get a new string of two characters from a given string

For more Practice: Solve these Related Problems:

  • Write a C# program to extract the first two characters from a string only if they form a valid chemical symbol.
  • Write a C# program to extract the first and last characters from a string if they match specific conditions.
  • Write a C# program to check if the first two characters form "PH" or "ph", case-insensitively.
  • Write a C# program to return a string only if it begins with "PH" and is at least 3 characters long.

Go to:


PREV : Remove 'HP' from String.
NEXT : Largest and Lowest of Three Integers.

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.