C# String Manipulation
C# String Manipulation
Lecture 9
Lecture overview
String formatting Stringbuilder and string methods Regular expressions
String formatting
String.Format(formatstring, arguments)
Also supported by Console.WriteLine() and others
StringBuilder
Strings are immutable objects Whenever a new string created, it uses a new memory location
This happens whenever strings are concatenated, trimmed, characters replaced, etc. Inefficient if a large string built by many small changes
Regular expressions
A regular expression (regex) is a compact way of representing a certain type of pattern
For most patterns, multiple equivalent regexes exist
Fundamental operation: regex matching deciding if a given input string can be mapped to the pattern Studied by complexity theory simple to match Many applications, among them
Used by compilers as a first step of program analysis Various popular Unix commands such as grep In web programming mostly for validating user input
CS 638 Web Programming Estan & Kivolowitz
Regular expressions in C#
Implemented by the class System.Text.RegularExpressions.Regex Constructor accepts a string describing the regular expression that is compiled to a representation used for efficient matching Important methods
IsMatch(string input) checks if input string matches Replace(string input, string replacement) replaces all matches of the regular expression in input Split(string input) splits input interpreting each match of the regex as a separator
C# programming
Lectures 6 - 9
Application structure
Namespaces similar to Java packages, but decoupled from how source code is structured Multiple classes can be defined in a single file, name of classes unrelated to file name C# partial classes a class defined in multiple files Assemblies similar to jar files C#s keyword internal is like Javas protected grants access to others from same assembly
In C# protected grants access to derived classes
Value types
C# has structs which are value types
new is optional (no memory allocation, calls constructor)
Generics in C# can also use value types (not just classes as in Java) Parameter passing
Java passes all parameters by value What does it mean to pass a reference type by value? C# allows passing by reference and output parameters for both value and reference types
Operator overloading supported in C#, not in Java C# replaces the implements and extends keywords with : C# refers to the base class as base, not super
CS 638 Web Programming Estan & Kivolowitz
Concepts
Event-driven programming
Extending applications with new event handlers
C# objects can have properties (use of accessors) C# has delegates C# has keywords const and readonly
Debugging breakpoints, stepping through program, watches, assertions Using language features that make it easier for the compiler to catch mistakes
Enums, const, readonly
Operator overloading can help or harm Naming conventions (for interface names)
CS 638 Web Programming Estan & Kivolowitz