
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to Initialize and Compare Strings in C#?
To initializes a string in C# is an easy task. Let’s say you want to set a name “Amit”, for that, initialize your string as.
String str1 = "Hello, World!";
To compare strings, use the the following C# method.
public static int Compare(string str1, string str2)
To compare, if −
String.Compare(str1, str2) == 0
If the above is equal to 0, then both the strings are equal.
The above method compares two specified string objects and returns an integer that indicates their relative position in the sort order.
The following is an example that shows the comparison of one string to another.
Example
using System; namespace Demo { class Program { static void Main(string[] args) { string str1 = "John"; string str2 = "Andy"; if (String.Compare(str1, str2) == 0) { Console.WriteLine(str1 + " and " + str2 + " are equal strings."); } else { Console.WriteLine(str1 + " and " + str2 + " are not equal strings."); } Console.ReadKey() ; } } }
Output
John and Andy are not equal strings.
- Related Articles
- How to initialize and compare strings?
- How to Initialize and Compare Strings in Java?
- How to declare and initialize constant strings in C#?
- How to compare strings in Java?
- How to compare date strings in Python?
- How to compare two strings in Golang?
- How to compare two strings in Perl?
- Compare two strings lexicographically in C#
- C++ Program to Compare two strings lexicographically
- What is a string? Declare and initialize the strings in C language
- How to compare two strings using regex in Python?
- How to initialize variables in C#?
- How to declare and initialize a dictionary in C#?
- How to declare and initialize a list in C#?
- How do I compare strings in Java?

Advertisements