c sharp Logo

C# String


Strings in C#

Strings are a fundamental data type in C# used to represent sequences of characters. They are immutable, meaning that once created, their contents cannot be changed. Strings are stored in memory and can be manipulated using various methods and operators.

String Concatenation

String concatenation combines multiple strings into a single string. The + operator is commonly used for concatenation. For instance:

string greeting = "Hello, " + "World!";

Console.WriteLine(greeting); // Output: Hello, World!

 

String Interpolation

String interpolation is a more concise and readable way to combine strings and expressions. It uses the $ symbol and curly braces to embed expressions within the string. For example:

string name = "Alice";

string age = "30";

Console.WriteLine($"Hello, {name}! You are {age} years old.");

// Output: Hello, Alice! You are 30 years old.

 

String Access

Individual characters within a string can be accessed using index notation. Indices start from 0, and the last index is the length of the string minus 1. For instance:

string message = "Welcome!";

char firstCharacter = message[0]; // firstCharacter = 'W'

char lastCharacter = message[message.Length - 1]; // lastCharacter = '!'

 

Special Characters

Special characters, such as quotation marks ("), backslashes (\), and newline characters (\n), require escaping when used within strings. Escaping involves preceding the special character with a backslash (\) to indicate its literal interpretation. For example:

string quote = "He said, \"That's a great idea!\"";

Console.WriteLine(quote); // Output: He said, "That's a great idea!"

 

Additional String Operations

C# provides various methods for manipulating strings, including:

  • Length: Returns the length of the string.
  • ToLower() and ToUpper(): Converts the string to lowercase or uppercase, respectively.
  • Trim(): Removes leading and trailing whitespace characters.
  • Replace(oldChar, newChar): Replaces all occurrences of oldChar with newChar in the string.
  • IndexOf(substring): Returns the first index of substring within the string, or -1 if not found.
  • Contains(substring): Checks if the string contains the specified substring.