Understanding C# String Basics

Sep 13, 2024

C# Strings Lecture Notes

Introduction to Strings

  • Strings are sequences of characters.
  • Defined in C# using double quotes, e.g., "Hello World".
  • Each character (like 'A', 'B', 'C') is an individual unit in a string.

String Declaration

  • Example: string firstFriend = "Maria";
    • string: Data type.
    • firstFriend: Variable name.
    • Maria: Value stored in the variable.
    • ;: Semicolon denotes the end of the statement (similar to a period in a sentence).

Variable Naming

  • Variables can be named anything (e.g., firstFriend, f).
  • The choice of name should be meaningful.

Console Output

  • Using Console.WriteLine to output strings.
  • Example: Console.WriteLine($"My friends are {firstFriend} and {secondFriend}");
    • $: Indicates string interpolation.
    • Curly braces {} are used to embed variable values within strings.

String Interpolation vs. Concatenation

  • String Interpolation: Easier to read and write, substitutes variable values directly.
  • Concatenation: Joining strings using + operator.
    • Example: "My friends are " + firstFriend + " and " + secondFriend;
  • Both methods achieve the same goal but interpolation is preferred for readability.

Error Handling in C# Strings

  • C# is a strongly typed language, providing compile-time error checking.
  • Errors highlighted immediately (red squiggles for errors, yellow for warnings) in the IDE.

Trimming Strings

  • Trimming removes whitespace from the start and end of strings.
  • Example: firstFriend = firstFriend.Trim();
  • Whitespace outside of quotes does not affect the string.
  • Both leading and trailing spaces can be removed using .Trim() method.

Intellisense in C#

  • Provides code completion and helps in writing code efficiently by suggesting methods and properties as you type.

Practical Example of Trimming

  • To trim strings in C#:
    • string firstFriend = " Maria "; (with spaces).
    • firstFriend = firstFriend.Trim(); to remove spaces.
  • Check results using Console.WriteLine() after trimming.

Conclusion

  • C# strings are powerful and flexible.
  • String manipulation techniques like interpolation and trimming are essential for effective coding.