C# String

String

Strings are fundamental in almost every programming task. In C#, the string class represents text as a sequence of Unicode characters. This tutorial will provide an overview of working with strings in C#.

1. Declaring and Initializing Strings

string name = "Alice"; string greeting = "Hello, world!"; 

2. String Properties and Methods

  • Length: Returns the number of characters in the string.

    int length = name.Length; // Outputs: 5 
  • Concatenation: You can concatenate strings using the + operator.

    string fullName = "Alice" + " " + "Brown"; 

    Or use the string.Concat() method:

    string fullName = string.Concat("Alice", " ", "Brown"); 
  • Substring: Extract a substring from a string.

    string part = greeting.Substring(7, 5); // Outputs: "world" 
  • Replace: Replace occurrences of a specified substring.

    string newGreeting = greeting.Replace("world", "Alice"); // Outputs: "Hello, Alice!" 
  • ToLower and ToUpper: Convert to lowercase or uppercase.

    string upper = name.ToUpper(); // Outputs: "ALICE" string lower = name.ToLower(); // Outputs: "alice" 

3. String Interpolation

Introduced in C# 6, string interpolation provides a more readable and convenient syntax to embed expression values directly into string literals.

int age = 25; string interpolated = $"My name is {name} and I am {age} years old."; 

4. Checking for Null or Empty Strings

To check if a string is null or empty:

if (string.IsNullOrEmpty(name)) { Console.WriteLine("Name is not set."); } 

To also check for whitespace:

if (string.IsNullOrWhiteSpace(name)) { Console.WriteLine("Name is not set or is just whitespace."); } 

5. Comparison

When comparing strings, it's essential to know if you want a case-sensitive or case-insensitive comparison.

bool areEqualCaseSensitive = string.Equals("Alice", "alice"); // Outputs: false bool areEqualCaseInsensitive = string.Equals("Alice", "alice", StringComparison.OrdinalIgnoreCase); // Outputs: true 

6. Splitting and Joining

  • Split:

    string data = "apple,banana,cherry"; string[] fruits = data.Split(','); 
  • Join:

    string[] words = { "Hello", "world!" }; string sentence = string.Join(" ", words); // Outputs: "Hello world!" 

7. Verbatim Strings

Use the @ symbol for verbatim strings, which don't treat backslashes as escape characters.

string filePath = @"C:\Documents\Report.txt"; 

8. StringBuilder

For scenarios where you need to manipulate strings extensively (like in loops), the StringBuilder class is more efficient than using regular strings because strings are immutable.

StringBuilder sb = new StringBuilder(); sb.Append("Hello"); sb.AppendLine("World"); string result = sb.ToString(); // Outputs: "Hello\nWorld\n" 

Conclusion

This tutorial provides a basic overview of working with strings in C#. The string class in C# is versatile and equipped with many methods and properties to simplify various text-processing tasks. Familiarizing oneself with these features will be beneficial for many programming scenarios.


More Tags

css-float height manytomanyfield api-platform.com cancellation-token jackson2 yum kendo-listview webdav xcodebuild

More Programming Guides

Other Guides

More Programming Examples