techmore.in

C# - Strings

In C#, strings are sequences of characters used to represent text. They are a fundamental part of programming and come with a variety of methods and properties for manipulating and analyzing text. Here’s a detailed guide on working with strings in C#:

1. Declaring and Initializing Strings

You can declare and initialize strings using double quotes.

Syntax:

csharp
string str = "Hello, World!";

2. String Operations

Concatenation

You can concatenate strings using the + operator or the String.Concat method.

csharp
string firstName = "John"; string lastName = "Doe"; string fullName = firstName + " " + lastName; // "John Doe"

Interpolation

String interpolation provides a way to embed expressions within string literals, using curly braces {}.

csharp
string name = "Alice"; int age = 30; string message = $"Name: {name}, Age: {age}"; // "Name: Alice, Age: 30"

Formatting

You can use String.Format to create formatted strings.

csharp
string formatString = "Name: {0}, Age: {1}"; string formattedMessage = String.Format(formatString, name, age); // "Name: Alice, Age: 30"

3. Common String Methods

Length

Gets the number of characters in the string.

csharp
int length = str.Length; // Length of the string

Substring

Extracts a substring from the string.

csharp
string sub = str.Substring(7, 5); // "World"

IndexOf

Finds the index of the first occurrence of a specified substring.

csharp
int index = str.IndexOf("World"); // 7

Replace

Replaces all occurrences of a specified substring with another substring.

csharp
string replaced = str.Replace("World", "C#"); // "Hello, C#!"

ToUpper and ToLower

Converts the string to uppercase or lowercase.

csharp
string upper = str.ToUpper(); // "HELLO, WORLD!" string lower = str.ToLower(); // "hello, world!"

Trim

Removes leading and trailing whitespace from the string.

csharp
string trimmed = " Hello ".Trim(); // "Hello"

Split

Splits the string into an array of substrings based on a delimiter.

csharp
string[] words = str.Split(' '); // ["Hello,", "World!"]

Join

Concatenates elements of an array into a single string with a specified delimiter.

csharp
string[] names = { "John", "Jane", "Doe" }; string joined = String.Join(", ", names); // "John, Jane, Doe"

Contains

Checks if a specified substring is present in the string.

csharp
bool contains = str.Contains("World"); // true

4. String Comparison

Strings can be compared using various methods, such as Equals, Compare, and CompareOrdinal.

Equals

Compares the string with another string for equality.

csharp
bool isEqual = str.Equals("Hello, World!"); // true

Compare

Compares two strings and returns an integer indicating their relative order.

csharp
int comparison = String.Compare("apple", "banana"); // < 0

CompareOrdinal

Compares two strings using ordinal (culture-insensitive) comparison.

csharp
int ordinalComparison = String.CompareOrdinal("apple", "banana"); // < 0

5. String Builder

For scenarios where you need to perform many modifications to a string, consider using StringBuilder. It is more efficient than using string concatenation in a loop.

csharp
using System.Text; StringBuilder sb = new StringBuilder(); sb.Append("Hello"); sb.Append(" "); sb.Append("World"); string result = sb.ToString(); // "Hello World"

6. Escape Sequences

Use escape sequences to represent special characters within strings.

  • \": Represents a double quote.
  • \\: Represents a backslash.
  • \n: Represents a newline.
  • \t: Represents a tab.
csharp
string text = "He said, \"Hello, World!\"\nThis is a new line.";

7. Verbatim Strings

Verbatim strings, defined with @, ignore escape sequences and allow multi-line strings.

csharp
string path = @"C:\Users\Name\Documents"; string multiLine = @"Line 1 Line 2 Line 3";

8. String Interpolation (Advanced)

String interpolation supports more advanced formatting options.

csharp
decimal price = 123.4567m; string formattedPrice = $"Price: {price:C2}"; // "Price: $123.46"

Summary

In C#, strings are powerful and versatile for handling text. You can perform a wide range of operations, from basic concatenation and formatting to advanced manipulations using methods like Substring, Replace, and Split. For efficient string modifications, use StringBuilder. Understanding and using these string operations effectively will enhance your ability to work with text in C# applications.