C# Strings

In C#, a string is a sequence of characters. It is a reference type and is represented by the string keyword. Strings are used to store and manipulate text data in C#.

Here are some key points about C# strings:

  1. Declaration and Initialization:

string myString = "Hello, World!"; // Declaration and initialization
string emptyString = string.Empty; // Empty string
string nullString = null; // Null string

2. String Concatenation:

string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // Concatenation using the + operator

3. String Interpolation:

string message = $"My name is {fullName}.";

4. String Length:

int length = myString.Length; // Length of the string

5. Accessing Characters:

char firstChar = myString[0]; // Accessing the first character

6. Common String Methods:

    • string.ToUpper(): Converts the string to uppercase.
    • string.ToLower(): Converts the string to lowercase.
    • string.Contains(string): Checks if a substring exists within the string.
    • string.Substring(startIndex, length): Retrieves a substring from the original string.
    • string.Replace(oldValue, newValue): Replaces occurrences of a specified string with another string.
    • string.Split(delimiters): Splits the string into an array of substrings based on the specified delimiters.
    • 7. String Comparison:

string str1 = "Hello";
string str2 = "hello";
bool areEqual = str1.Equals(str2, StringComparison.OrdinalIgnoreCase); // Case-insensitive comparison

8. String Formatting:

string formattedString = string.Format("The value is {0:C2}", 123.45); // Formatting numeric values

9. Immutable Nature: Strings in C# are immutable, meaning once a string is created, it cannot be changed. Any modification operations on a string create a new string object.

These are some of the basic concepts and operations related to strings in C#. There are many more methods and techniques available to work with strings, which you can explore in the C# documentation or relevant programming resources.

string vs String:

In C#, both string and String refer to the same type, which represents a sequence of characters. The string keyword is an alias for the System.String class defined in the .NET framework.

The choice between using string or String is purely a matter of personal preference. Most C# developers tend to use the string keyword, which is considered more consistent with other built-in types like int, bool, etc. However, both string and String can be used interchangeably, and the compiler treats them as identical.

For example, the following declarations are equivalent:

string myString = "Hello"; // Using the 'string' keyword
String myString = "Hello"; // Using the 'String' class

It’s worth noting that in C#, the recommended convention for naming types is to use PascalCase, where the first letter of each word is capitalized. However, for the string type, the convention is to use lowercase string.

In summary, string and String refer to the same string type in C#, and you can use them interchangeably. It’s generally more common and recommended to use the string keyword for consistency with other built-in types in C#.

C# String Example:

Certainly! Here’s an example that demonstrates various operations and methods you can perform with strings in C#:

using System;

class Program
    static void Main()
        // Declaration and initialization
        string message = "Hello, World!";

        // Length of the string
        int length = message.Length;
        Console.WriteLine($"Length: {length}");

        // Accessing characters
        char firstChar = message[0];
        Console.WriteLine($"First character: {firstChar}");

        // String concatenation
        string name = "Alice";
        string greeting = "Hi, " + name + "!";

        // String interpolation
        int age = 30;
        string info = $"Name: {name}, Age: {age}";

        // String methods
        string uppercase = message.ToUpper();
        string lowercase = message.ToLower();
        bool containsHello = message.Contains("Hello");
        string substring = message.Substring(7, 5);
        string replaced = message.Replace("World", "Universe");
        string[] words = message.Split(',');

        Console.WriteLine($"Contains 'Hello': {containsHello}");
        Console.WriteLine($"Split words: {string.Join(", ", words)}");

        // String comparison
        string str1 = "Hello";
        string str2 = "hello";
        bool areEqual = str1.Equals(str2, StringComparison.OrdinalIgnoreCase);
        Console.WriteLine($"Equal strings: {areEqual}");

        // String formatting
        double price = 12.345;
        string formattedPrice = string.Format("The price is: {0:C2}", price);


Length: 13
First character: H
Hi, Alice!
Name: Alice, Age: 30
hello, world!
Contains 'Hello': true
Hello, Universe!
Split words: Hello, World!
Equal strings: true
The price is: $12.35

In this example, we declare a message string and demonstrate various string operations such as finding the length, accessing characters, concatenation, interpolation, using string methods (like ToUpper(), ToLower(), Contains(), Substring(), Replace(), and Split()), string comparison, and string formatting.

Feel free to modify and explore the code to understand different string manipulation techniques in C#.

C# String methods:

Certainly! Here are some commonly used methods available for manipulating strings in C#:

  1. Length: Returns the number of characters in a string.
string message = "Hello, World!";
int length = message.Length;

2. ToUpper and ToLower: Converts the string to uppercase or lowercase.

string uppercase = message.ToUpper();
string lowercase = message.ToLower();

3. Contains: Checks if a specified substring exists within the string.

bool containsHello = message.Contains("Hello");

4. Substring: Retrieves a substring from the original string based on the specified starting index and length.Substring: Retrieves a substring from the original string based on the specified starting index and length.

string substring = message.Substring(7, 5); // Retrieves "World"

5. Replace: Replaces all occurrences of a specified string with another string.

string replaced = message.Replace("World", "Universe");

6. Split: Splits the string into an array of substrings based on a specified delimiter.

string[] words = message.Split(','); // Splits the string into ["Hello", " World!"]

7. Trim, TrimStart, and TrimEnd: Removes leading and trailing whitespace characters from the string.

string input = "   Hello, World!   ";
string trimmed = input.Trim(); // "Hello, World!"
string trimmedStart = input.TrimStart(); // "Hello, World!   "
string trimmedEnd = input.TrimEnd(); // "   Hello, World!"

8. IndexOf and LastIndexOf: Returns the index of the first or last occurrence of a specified substring within the string.

int firstIndex = message.IndexOf("World"); // 7
int lastIndex = message.LastIndexOf("o"); // 8

9. StartsWith and EndsWith: Checks if the string starts or ends with the specified substring.

bool startsWithHello = message.StartsWith("Hello"); // true
bool endsWithWorld = message.EndsWith("World"); // true

10. Concat: Concatenates multiple strings into a single string.

string name = "John";
string greeting = string.Concat("Hello, ", name, "!"); // "Hello, John!"

11. Join: Concatenates an array of strings into a single string, using a specified separator.

string[] names = { "John", "Jane", "Bob" };
string joinedNames = string.Join(", ", names); // "John, Jane, Bob"

These are just a few examples of the many methods available for manipulating strings in C#. Each method provides a different way to modify, search, or extract information from a string. For more details on these methods and additional string manipulation techniques, refer to the official C# documentation.