C# String

In C#, a string is a sequence of characters represented by the string keyword. A string can contain any combination of letters, numbers, symbols, and whitespace characters.

Creating Strings

You can create a string by enclosing a sequence of characters in double quotes:

1string myString = "Hello, World!";

You can also create a string by calling the ToString() method on an object:

1int myNumber = 42; 2string myString = myNumber.ToString();

C# String Functions

C# provides a variety of built-in functions that allow you to manipulate strings. Here are some of the most commonly used string functions:

Length

The Length function returns the number of characters in a string:

1string myString = "Hello, World!"; 2int length = myString.Length; // returns 13

Concatenation

The + operator can be used to concatenate two strings:

1string firstName = "William"; 2string lastName = "Max"; 3string fullName = firstName + " " + lastName; // returns "William Max"

You can also use the Concat function to concatenate multiple strings:

1string firstName = "William"; 2string lastName = "Max"; 3string middleName = "Q"; 4string fullName = string.Concat(firstName, " ", middleName, " ", lastName); // returns "William Q Max"

Substring

The Substring function returns a substring of a string. The first argument is the starting index, and the second argument is the length of the substring:

1string myString = "Hello, World!"; 2string substring = myString.Substring(0, 5); // returns "Hello"

ToUpper and ToLower

The ToUpper function returns a copy of a string in all uppercase:

1string myString = "Hello, World!"; 2string uppercase = myString.ToUpper(); // returns "HELLO, WORLD!"

The ToLower function returns a copy of a string in all lowercase:

1string myString = "Hello, World!"; 2string lowercase = myString.ToLower(); // returns "hello, world!"

Trim

The Trim function removes all leading and trailing whitespace characters from a string:

1string myString = " Hello, World! "; 2string trimmed = myString.Trim(); // returns "Hello, World!"

Replace

The Replace function replaces all occurrences of a substring with another string:

1string myString = "Hello, World!"; 2string replaced = myString.Replace("Hello", "Hi"); // returns "Hi, World!"

Split

The Split function splits a string into an array of substrings based on a delimiter:

1string myString = "apple,banana,orange"; 2string[] fruits = myString.Split(','); // returns ["apple", "banana", "orange"]