C# program for character comparison

C# program for character comparison: Here, we are writing a C# program – it will input the characters and compare them.
Submitted by IncludeHelp, on April 09, 2019 [Last updated : March 18, 2023]

Input characters and compare them using C# program.

Prerequisite: Methods to input a single character in C#

C# code to compare two characters

Here, we are asking for two characters from the user – and checking whether they are the same characters or not?

// C# program for character comparison 

using System;
using System.IO;
using System.Text;

namespace IncludeHelp {
  class Test {
    // Main Method 
    static void Main(string[] args) {
      char ch1;
      char ch2;

      //input characters
      Console.Write("Enter a character: ");
      ch1 = Console.ReadLine()[0];
      Console.Write("Enter another character: ");
      ch2 = Console.ReadLine()[0];

      //comparing characters
      if (ch1 == ch2)
        Console.WriteLine("Input characters are the same");
      else
        Console.WriteLine("Input characters are not the same");

      //hit ENTER to exit the program
      Console.ReadLine();
    }
  }
}

Output

First run:
Enter a character: A
Enter another character: A
Input characters are the same

Second run:
Enter a character: A
Enter another character: X
Input characters are not the same

C# code to compare characters in a string

Here, we are asking for a string from the user – and printing only vowels by comparing each character of the string with vowel characters.

// C# program for character comparison 

using System;
using System.IO;
using System.Text;

namespace IncludeHelp {
  class Test {
    // Main Method 
    static void Main(string[] args) {
      string str;

      //input string
      Console.Write("Enter a string: ");
      str = Console.ReadLine();

      //printing the string
      Console.WriteLine("Input string is {0}", str);

      //printing vowels 
      Console.WriteLine("Vowels are...");
      foreach(char ch in str) {
        if (ch == 'A' || ch == 'a' || ch == 'E' || ch == 'e' ||
          ch == 'I' || ch == 'i' || ch == 'O' || ch == 'o' ||
          ch == 'U' || ch == 'u') {
          Console.Write(ch);
        }
      }

      //hit ENTER to exit the program
      Console.ReadLine();
    }
  }
}

Output

Enter a string: IncludeHelp.com
Input string is IncludeHelp.com
Vowels are...
Iueeo

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.