C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In C#, the string
class represents a sequence of characters. It is an object of the System.String class, and is one of the most commonly used data types. In this tutorial, we'll cover the basics of working with strings in C#.
To create a string, use double quotes ("") and assign it to a variable:
string myString = "Hello, world!";
To concatenate strings, use the '+' operator:
string firstName = "John"; string lastName = "Doe"; string fullName = firstName + " " + lastName; // "John Doe"
C# supports string interpolation, which allows you to embed expressions within string literals:
string name = "John"; int age = 30; string info = $"My name is {name} and I am {age} years old."; // "My name is John and I am 30 years old."
Escape sequences are used to represent special characters in a string:
\"
�C Double quote\\
�C Backslash\n
�C New line\t
�C Tabstring message = "This is a line with a \"quote\" and a \\backslash."; // "This is a line with a "quote" and a \backslash."
C# provides many useful string methods, such as:
ToUpper()
: Convert the string to uppercaseToLower()
: Convert the string to lowercaseTrim()
: Remove whitespace from the beginning and end of the stringSubstring()
: Extract a portion of the stringIndexOf()
: Find the index of a character or substringReplace()
: Replace all occurrences of a substring with another substringstring original = " Hello, World! "; string upper = original.ToUpper(); // " HELLO, WORLD! " string lower = original.ToLower(); // " hello, world! " string trimmed = original.Trim(); // "Hello, World!" string substring = original.Substring(0, 5); // " Hello" int index = original.IndexOf('W'); // 8 string replaced = original.Replace("World", "C#"); // " Hello, C#! "
Use the ==
operator to compare strings for equality, and the !=
operator to check for inequality:
string str1 = "hello"; string str2 = "world"; bool areEqual = str1 == str2; // false bool areNotEqual = str1 != str2; // true
To compare strings case-insensitively, use the String.Equals()
method:
string str1 = "Hello"; string str2 = "hello"; bool areEqual = String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase); // true
This tutorial is just the beginning of your journey with strings in C#. There are many more methods and features available in the System.String
class, so be sure to explore the official documentation for more information.
How to use strings in C#
Strings are sequences of characters and are widely used in C# for text manipulation.
string greeting = "Hello, C# strings!";
String manipulation in C#
Perform various string manipulations, like changing case and reversing.
string original = "C#"; string manipulated = original.ToLower(); // Change to lowercase
Concatenating strings in C#
Combine strings using the +
operator or String.Concat
method.
string firstName = "John"; string lastName = "Doe"; string fullName = firstName + " " + lastName; // Concatenation
String interpolation in C#
Use string interpolation for more readable and expressive string formatting.
string result = $"{firstName} {lastName}"; // Interpolation
Working with string literals in C#
String literals are constant values embedded directly in the code.
string literal = "This is a string literal";
Substring operations in C# strings
Extract substrings using Substring
method.
string text = "C# Programming"; string substring = text.Substring(2, 5); // Extract " Programming"
Searching and replacing in C# strings
Use IndexOf
, LastIndexOf
, Replace
for searching and replacing.
string sentence = "C# is awesome!"; int index = sentence.IndexOf("awesome"); // Find index string replaced = sentence.Replace("awesome", "fantastic"); // Replace
String comparison in C#
Compare strings using methods like Equals
, Compare
, and operators.
string str1 = "C#"; string str2 = "c#"; bool areEqual = str1.Equals(str2, StringComparison.OrdinalIgnoreCase); // Case-insensitive comparison
String formatting in C#
Format strings using String.Format
or interpolated strings.
int age = 25; string formatted = String.Format("My age is {0}", age);
Common string methods in C#
Explore common string methods like ToUpper
, ToLower
, Trim
, etc.
string text = " C# is fun! "; string trimmed = text.Trim(); // Remove leading and trailing whitespaces
StringBuilder vs. String concatenation in C#
Use StringBuilder
for efficient string concatenation in loops.
StringBuilder builder = new StringBuilder(); for (int i = 0; i < 1000; i++) { builder.Append(i.ToString()); } string result = builder.ToString();
Unicode and character encoding in C# strings
Strings in C# are Unicode by default, supporting a wide range of characters.
string unicodeString = "C# and Unicode ❤";
Handling null and empty strings in C#
Check for null or empty strings before performing operations.
string userInput = GetUserInput(); if (!string.IsNullOrEmpty(userInput)) { // Perform operations }