Topics covered:

  • What is String?
  • Creating and Using Strings
    • Declaring, Creating, Reading and Printing
  • Manipulating Strings
    • Comparing, Concatenating, Searching, Extracting Substrings, Splitting
  • Other String Operations
    • Replacing Substrings, Deleting Substrings, Changing Character Casing, Trimming
  • Building and Modifying Strings
    • Why the + Operator is Slow?
    • Using the StringBuilder Class
  • Formatting Strings
    • Formatting Numbers, Dates and Currency
  • Cultures and Culture-Sensitive Formatting
    • Accessing and Assigning the Current Culture
    • Parsing Numbers and Dates

Video (in Bulgarian)

Presentation Content

What Is String?

  • Strings are sequences of characters
  • Each character is a Unicode symbol
  • Represented by the string data type in C# ( System.String )
  • Example: string s = "Hello, C#";
H e l l o ,   C #

The System.String Class

  • Strings are represented by System.String objects in .NET Framework
    • String objects contain an immutable (read-only) sequence of characters
    • Strings use Unicode to support multiple languages and alphabets
  • Strings are stored in the dynamic memory ( managed heap )
  • System.String is reference type
  • String objects are like arrays of characters ( char[] )
    • Have fixed length ( String.Length )
    • Elements can be accessed directly by index
      • The index is in the range [0...Length-1]
0 1 2 3 4 5
H e l l o !

Declaring Strings

  • Several ways of declaring string variables:
    • Using the C# keyword string
    • Using the .NET’s fully qualified class name System.String
    • The next three declarations are equivalent
      • string str1;
      • System.String str2;
      • String str3;

Creating Strings

  • Before initializing a string variable has null value
  • Strings can be initialized by:
    • Assigning a string literal to the string variable
    • Assigning the value of another string variable
    • Assigning the result of operation of type string
  • Not initialized variables has value of null
  • Assigning a string literal
    • string s; // s is equal to null
  • Assigning from another string variable
    • string s = "I am a string literal!";
  • Assigning from the result of string operation
    • string s = 42.ToString();

Comparing Strings

  • Several ways to compare two strings:
    • Dictionary-based string comparison
      • Case-insensitive
      • Case-sensitive
  • Equality checking by operator ==
    • Performs case-sensitive compare
  • Using the case-sensitive Equals() method
    • The same effect like the operator ==

Concatenating Strings

  • There are two ways to combine strings:
    • Using the Concat() method
    • Using the + or the += operators
  • Any object can be appended to a string

Searching in Strings

  • Finding a character or substring within given string
    • First occurrence
      • IndexOf(string str)
    • First occurrence starting at given position
      • IndexOf(string str, int startIndex)
    • Last occurrence
      • LastIndexOf(string)
0 1 2 3 4 5 6 7 8 9 10 11 12 13
C #   P r o g r a m m i n g

Extracting Substrings

  • Extracting substrings
    • str.Substring(int startIndex, int length)
    • str.Substring(int startIndex)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
C : \ P i c s \ R i l a 2 0 0 5 . j p g

Replacing and Deleting Substrings

  • Replace(string, string) – replaces all occurrences of given string with another
    • The result is new string (strings are immutable)
  • Re move ( index , length ) – deletes part of a string and produces new string as result

Constructing Strings

  • Strings are immutable !
    • C oncat() , R eplace() , T rim() , ... return new string, do not modify the old one
  • Do not use " + " for strings in a loop!
    • It runs very, very inefficiently!
  • StringBuilder keeps a buffer memory, allocated in advance
    • Most operations use the buffer memory and do not allocate new objects

How the + Operator Performs String Concatenations?

  • Consider the following string concatenation:
  • It is equivalent to this code:
  • Several new objects are created and left to the garbage collector for deallocation
    • What happens when using + in a loop?

The StringBuilder Class

  • StringBuilder(int _ _ capacity) constructor allocates in advance buffer of given size
    • By default 16 characters are allocated
  • Capacity holds the currently allocated space (in characters)
  • this[int _ _ index] (indexer in C#) gives access to the char value at given position
  • Length holds the length of the string in the buffer
  • Append(…) appends a string or another object after the last character in the buffer
  • Remove (int start Index , int length ) removes the characters in given range
  • Insert(int index , string str) inserts given string (or object) at given position
  • Replace(string oldStr, string newStr) replaces all occurrences of a substring
  • ToString() converts the StringBuilder to String

Method ToString()

  • All classes in C# have public virtual method ToString()
    • Returns a human-readable, culture-sensitive string representing the object
    • Most .NET Framework types have own implementation of ToString()
      • int , float , bool , DateTime
  • We can apply specific formatting when converting objects to string
    • ToString(formatString) method

Formatting Strings

  • The formatting strings are different for the different types
  • Some formatting strings for numbers:
    • D – number (for integer types)
    • C – currency (according to current culture)
    • E – number in exponential notation
    • P – percentage
    • X – hexadecimal number
    • F – fixed point (for real numbers)

Formatting Dates

  • Dates have their own formatting strings
    • d , dd – day (with/without leading zero)
    • M , MM – month
    • yy , yyyy – year (2 or 4 digits)
    • h , HH , m , mm , s , ss – hour, minute, second
  • Cultures in .NET specify formatting / parsing settings specific to country / region / language

Summary

  • Strings are immutable sequences of characters (instances of System.String )
    • Declared by the keyword string in C#
    • Can be initialized by string literals
  • Most important string processing members are:
    • Length, this[] , Compare(str1, str2) , IndexOf(str) , LastIndexOf(str) , Substring(startIndex, length) , Replace(oldStr, newStr) , Remove(startIndex, length) , ToLower() , ToUpper() , Trim()
  • Objects can be converted to strings and can be formatted in different styles (using ToString () method)
  • Strings can be constructed by using placeholders and formatting strings ( String.Format (…) )