Introduction
Strings in C# are sequences of characters used to represent text. The string
type in C# is an alias for System.String
, and it is a reference type. Strings in C# are immutable, meaning that once a string is created, it cannot be modified. Instead, any modifications to a string result in the creation of a new string.
Creating Strings
Declaration and Initialization
Strings can be created using string literals enclosed in double quotes.
string greeting = "Hello, World!";
Using the new
Keyword
You can also create strings using the new
keyword, though it is not common practice.
string greeting = new string("Hello, World!");
Common String Operations
Concatenation
Concatenation is the process of combining two or more strings into one.
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // Output: John Doe
Interpolation
String interpolation provides a way to format strings and embed expressions inside string literals.
string firstName = "John";
string lastName = "Doe";
string fullName = $"{firstName} {lastName}";
Console.WriteLine(fullName); // Output: John Doe
Formatting
The string.Format
method is used to format strings.
string firstName = "John";
string lastName = "Doe";
string fullName = string.Format("{0} {1}", firstName, lastName);
Console.WriteLine(fullName); // Output: John Doe
Length
The Length
property gets the number of characters in the string.
string greeting = "Hello, World!";
Console.WriteLine(greeting.Length); // Output: 13
Accessing Characters
You can access individual characters in a string using an index, starting from 0.
string greeting = "Hello, World!";
char firstChar = greeting[0];
Console.WriteLine(firstChar); // Output: H
Substrings
The Substring
method extracts a substring from a string.
string greeting = "Hello, World!";
string sub = greeting.Substring(7, 5);
Console.WriteLine(sub); // Output: World
Contains
The Contains
method checks if a string contains a specified substring.
string greeting = "Hello, World!";
bool containsWorld = greeting.Contains("World");
Console.WriteLine(containsWorld); // Output: True
Replace
The Replace
method replaces all occurrences of a specified substring with another substring.
string greeting = "Hello, World!";
string newGreeting = greeting.Replace("World", "C#");
Console.WriteLine(newGreeting); // Output: Hello, C#
Split
The Split
method splits a string into an array of substrings based on a specified delimiter.
string sentence = "This is a sample sentence.";
string[] words = sentence.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
}
Join
The Join
method concatenates an array of strings into a single string with a specified separator.
string[] words = { "This", "is", "a", "sample", "sentence." };
string sentence = string.Join(" ", words);
Console.WriteLine(sentence); // Output: This is a sample sentence.
Trim
The Trim
method removes leading and trailing whitespace from a string.
string paddedString = " Hello, World! ";
string trimmedString = paddedString.Trim();
Console.WriteLine(trimmedString); // Output: Hello, World!
String Comparison
Equals
The Equals
method compares two strings for equality.
string str1 = "Hello";
string str2 = "Hello";
bool areEqual = str1.Equals(str2);
Console.WriteLine(areEqual); // Output: True
Compare
The Compare
method compares two strings and returns an integer indicating their relative position in the sort order.
string str1 = "Hello";
string str2 = "World";
int result = string.Compare(str1, str2);
Console.WriteLine(result); // Output: -1 (str1 is less than str2)
CompareOrdinal
The CompareOrdinal
method compares two strings using ordinal (binary) sort rules.
string str1 = "Hello";
string str2 = "hello";
int result = string.CompareOrdinal(str1, str2);
Console.WriteLine(result); // Output: -32 (str1 is less than str2 in binary comparison)
Practical Example
Let’s create a practical example where we manipulate a string to extract, modify, and format text.
using System;
namespace StringManipulationExample
{
class Program
{
static void Main(string[] args)
{
string text = " C# is a great programming language. ";
// Trim leading and trailing spaces
string trimmedText = text.Trim();
Console.WriteLine($"Trimmed: '{trimmedText}'");
// Convert to uppercase
string upperText = trimmedText.ToUpper();
Console.WriteLine($"Uppercase: '{upperText}'");
// Extract substring
string substring = upperText.Substring(4, 5);
Console.WriteLine($"Substring: '{substring}'");
// Replace a word
string replacedText = trimmedText.Replace("great", "powerful");
Console.WriteLine($"Replaced: '{replacedText}'");
// Split into words
string[] words = replacedText.Split(' ');
Console.WriteLine("Words:");
foreach (string word in words)
{
Console.WriteLine(word);
}
// Join words into a single string
string joinedText = string.Join(" ", words);
Console.WriteLine($"Joined: '{joinedText}'");
// Format a new string
string formattedText = string.Format("Original: '{0}', Modified: '{1}'", text, joinedText);
Console.WriteLine($"Formatted: '{formattedText}'");
}
}
}
Output
Trimmed: 'C# is a great programming language.'
Uppercase: 'C# IS A GREAT PROGRAMMING LANGUAGE.'
Substring: 'IS A '
Replaced: 'C# is a powerful programming language.'
Words:
C#
is
a
powerful
programming
language.
Joined: 'C# is a powerful programming language.'
Formatted: 'Original: ' C# is a great programming language. ', Modified: 'C# is a powerful programming language.'
Conclusion
Strings in C# are versatile and powerful, offering a wide range of methods for manipulation and comparison. By understanding how to use strings effectively, you can handle text data efficiently in your applications. Whether you need to concatenate, format, compare, or modify strings, C# provides robust support for these operations.