Strings in C# Language
Strings are an integral part of virtually every programming language, and C# is no exception. In C#, a strin
g is a sequence of characters that represents text and is one of the most commonly used data types. In this post, we’ll explore the basics of working with strings in C# and provide examples to help you understand how to manipulate and use them effectively.Creating Strings
In C#, you can create strings using string literals enclosed in double quotation marks. For example:
string greeting = "Hello, World!";
You can also use the string
keyword to declare a string variable without initializing it immediately:
string name;
name = "John Doe";
String Concatenation
You can concatenate strings in C# using the +
operator. Here’s an example:
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // Output: John Doe
Alternatively, you can use string interpolation to embed expressions within a string using the $
symbol:
string age = "30";
string message = $"My name is {fullName} and I am {age} years old.";
Console.WriteLine(message); // Output: My name is John Doe and I am 30 years old.
String Methods
C# provides numerous methods for working with strings. Here are a few commonly used ones:
Length
You can determine the length of a string using the Length
property:
string text = "This is a sample text.";
int length = text.Length;
Console.WriteLine(length); // Output: 22
Substring
You can extract a portion of a string using the Substring
method:
string text = "This is a sample text.";
string substring = text.Substring(5, 2); // Start at index 5, take 2 characters
Console.WriteLine(substring); // Output: "is"
ToUpper and ToLower
You can change the case of a string using ToUpper
and ToLower
methods:
string text = "This is a sample text.";
string upperText = text.ToUpper();
string lowerText = text.ToLower();
Console.WriteLine(upperText); // Output: "THIS IS A SAMPLE TEXT."
Console.WriteLine(lowerText); // Output: "this is a sample text."
String Comparison
To compare strings in C#, you can use the ==
operator, but remember that it compares the references of the strings, not their contents. For content-based comparisons, you should use String.Equals
:
string str1 = "hello";
string str2 = "Hello";
bool areEqual = string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase);
Console.WriteLine(areEqual); // Output: true
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.