0% found this document useful (0 votes)
9 views62 pages

cs321 Winter 2023 Lecture 4 Strings

The document provides an overview of Object-Oriented Programming (OOP) concepts, focusing on classes and objects in C#. It explains the hierarchy of classes, variable types, casting, string manipulation, and various string functions, as well as the immutability of strings. Additionally, it includes examples, useful methods, and interview questions related to strings.

Uploaded by

mbielawski21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views62 pages

cs321 Winter 2023 Lecture 4 Strings

The document provides an overview of Object-Oriented Programming (OOP) concepts, focusing on classes and objects in C#. It explains the hierarchy of classes, variable types, casting, string manipulation, and various string functions, as well as the immutability of strings. Additionally, it includes examples, useful methods, and interview questions related to strings.

Uploaded by

mbielawski21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

TODAY’S GOAL

Deepen our understanding of Object-Oriented Programming and


Strings
WHAT IS AN OBJECT IN OOP?
An object is an instance of a class
A data type definition

What is a
A template for creating objects class in
OOP?
Describes methods and data
Classes in C#
• System.String is a class
• System.Object is a class
• System.Type is also a class
• A class is a kind of data type
• Classes describe the data and methods contained by “instances” of the class
• Instances of a class are values, known as objects
• Classes can derive from (inherit) another class (at most one)
• Classes without an explicit base class, derive from System.Object
Example of a Class Hierarchy

System.Object

System.String
Variables
• All variables have a fixed type determined at compile-time
• A variable refers to an instance of a type (or null)
• Variables may be initialized when declared (best practice)
• Variables may be reassigned (use sparingly)
• Variables cannot be assigned a value of an incorrect type
Parameters and Arguments

Function parameters are a special kind of variable (also called “formal arguments”)

When a function is invoked the function parameters are bound to values

Values provided during invocation to parameters are called arguments


This is indeed confusing!

The keyword “object” is a synonym for the type “System.Object”

Indicates that the accepted type of parameters, local variables, and return types is treated as a
System.Object

In an object-oriented programming, all, or most, values are also called objects.


Objects and Values
• Consider: var s = “hello”;
• This is an implicitly typed variable declaration statement.
• Implicitly typed because it uses the “var” keyword
• The variable declared is named “s”
• The following is equivalent:
• string s = “hello”.
A local variable declared with the
“var” keyword is implicitly typed
Implicitly
Requires initialization upon
Typed declaration
Variables
The variable takes the precise
type of the expression
Casting to Object
• Everything can be cast to an object:
• var x = (object)”Hello”;
• This is equivalent to:
• object x = “Hello”;
Upcast
• System.String derives from System.Object
• System.Object is called the base class
• System.String is called the derived class
• Any cast to a base class is called an upcast
• Upcasts are implicit: no conversion operator is required
• They are always successful (think about why)
Downcast
• Casting from a base class to a derived
class
• System.Object to System.String is a
downcast
• Downcasts are always explicit
• They may fail at run-time (think about
why)
The runtime type of an object
• This is the value returned by calling “GetType()”
• The run-time type of a value is unaffected by any casts
• it never changes.
WHAT DOES THE FOLLOWING DO?
Note: they are both equivalent
EITHER WAY WE GET AN ERROR!
Why? Because objects don’t have “Length” properties
A variable or expression of type
Types “T” only provides access to
methods and properties of T.
Restrict
Methods &
Properties Regardless of the run-time type
of the value
What does “.” mean?
• When calling a function it usually looks like “Console.WriteLine”
• What is the “.”
• What is to the left?
• What is to the right?
Member Access Expression (“.”)
• Getting a member associated with a type, namespace, or object
• That member might be a field, method, property, event, type, namespace
• Left-hand side might be an expression, type, namespace
• The member might be static or not
Expressions that cannot
be reduced
What are
Literals Like values embedded in
code
Escape Characters
• Escape characters are specially characters in string and character literals.
• \t – Tab
• \n – Newline
• \f – Form feed
• \” – Double Quotes
• \\ - Backslash
• \0 – Null character
String Literals
Regular string literals:
• use escape characters
• no embedded newlines

Verbatim string literals:


• no escape characters
• embedded newlines
• Prefix with @ symbol
Null Characters
• A C# string can contain any number of embedded null characters ('\0’).
• The null character has the ASCII code (and Unicode) of zero.
• This differs from C/C++ which uses null to indicate termination
• Not to be confused with the null keyword
Useful String Functions

01 02 03 04
String.IndexOf String.Substring String.Split String.Join
String.IndexOf()
String.IndexOf Demo
String.Substring
String.Substring Demo
String.Split
String.Split() Demo
Params: Variable Length Arguments
The params keywords means that I can do this instead as well: notice no array.
String.Join
String.Join Demo
Instance methods have the form
“expression.FunctionName(args)”
Invoking
Instance
versus Static Static method have the form
Methods “typename.FunctionName(args)”
WHY IS STRING.JOIN STATIC?
CONVERTING BYTES TO/FROM
STRINGS
BIT
CONVERTER
DOES NOT
WORK ON
STRINGS?!
string value = "\u00C4 \uD802\u0033 \u00AE"; byte[] bytes= System.Text.Encoding.UTF8.GetBytes(value);
System.Text.Encoding.UTF8.GetBytes(value);

Remember Encodings?
We need to choose one, such as

System.Text.Encoding.UTF8.GetBytes()

System.Text.Encoding.UTF16.GetBytes()

System.Text.Encoding.ASCIIEncoding.GetBytes()
String Constructors

String(Char, Int32) - Initializes a new instance of the String class to the value indicated by a
specified Unicode character repeated a specified number of times.

String(Char[]) - Initializes a new instance of the String class to the Unicode characters
indicated in the specified character array.
String Operators

+= String
+ String
concatenation == Equality != Inequality
concatenation
and assignment
They have a Length property

Strings are They support indexing using an


Like Arrays integer index

In other words you can get the


nth character using a subscript
Demo String Length and Indexing
A member that resembles a field

Wait, what May redirect to a field or to a function

is a May be read-only or read-write


property?
May be static or non-static
String objects are immutable:
they can't be changed after
they've been created
String
Immutability Methods and C# operators
either query a string or create
a new string object
StringBuilder class String.Format

So how do
you build String interpolation
expression
Concatenation

strings?
From an array of chars
What about memory?
• Do we care?
• If two strings return “equal” and have the same hash-code?
• They are effectively equal
• You could call “Object.ReferenceEquals()”, but don’t.
Indexers

An indexer allows a type instance to be indexed like an array or dictionary

An indexer can accept any type of parameters (like an int, string, object.)
String Formatting
• Before string interpolation we had string
formatting routines
• Like a safe and powerful version of the C
function sprintf().
• String.Format()
String Formatting
Formatting with String interpolation
The Null Literal
• The null keyword represents a reference that does not refer to an object.
• It has a special type (called the null type) but can be cast to any reference type
• Reference variables are assigned null by default
• In other words it means “no value”
• Different from the empty string (“”)
NullReferenceException
Checking if Strings are Null or Empty
STRING
QUERIES
Strings implement IEnumerable

This means you


Strings implement can loop through
“IEnumerable” the characters
with a foreach
Foreach
Foreach is a For Loop

https://learn.microsoft.com/en-us/dotnet/api/system.collections.ienumerable.getenumerator?view=net-7.0
Interview Questions with Strings
• Get all duplicated characters in a string.
• Get all unique characters in a string.
• Reverse a string.
• Reverse each word in a string
• Get the word count in a string
• Check if a string is a palindrome or not
• Check max occurrence of a character in the string.
• Get all possible substring in a string.
• Get the first char of each word in capital letter
• Check if two strings are anagrams
• Remove duplicated characters
• Check if a function has all unique characters
Review
• Do all variables have types?
• How is the type of an implicitly typed variable declaration determined?
• What does the “var” keyword indicate?
• Can I access methods specific to a string (like Length) on a variable of type “object”?
• Can a variable of type “object” refer to a “string” object?
• How can I determine the run-time type of an object?
• What is an instance of a class called?
• What does System.String inherit from?
• Casting from System.String to System.Object is an upcast or downcast?
• Are upcasts explicit or implicit?
• Can I change the type of a value?
• Are types valid expressions?
Next Class
• Collections
• Building our First Class

You might also like