Thanks to visit codestin.com
Credit goes to www.scribd.com

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

Cs321 Winter 2023 Lecture 4 Strings

The document provides an overview of Object-Oriented Programming (OOP) concepts, focusing on classes, objects, and string manipulation in C#. It explains the definitions of classes and objects, variable types, method parameters, and various string functions, including string formatting and immutability. Additionally, it covers casting, member access, and common string-related interview questions.

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 PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views62 pages

Cs321 Winter 2023 Lecture 4 Strings

The document provides an overview of Object-Oriented Programming (OOP) concepts, focusing on classes, objects, and string manipulation in C#. It explains the definitions of classes and objects, variable types, method parameters, and various string functions, including string formatting and immutability. Additionally, it covers casting, member access, and common string-related interview questions.

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 PPTX, 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 template for creating
objects
a 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
• Classesdescribe 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.Obj
ect

System.Stri
ng
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
•Castingfrom a base class to a
derived class
•System.Object to System.String
is a downcast
•Downcasts are always explicit
•Theymay 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
Types of type “T” only provides
Restrict access to methods and
properties of T.
Methods
& Regardless of the run-
Properties 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 lit


erals
:
• 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
Invoking form
“expression.FunctionName(
Instance args)”
versus
Static method have the
Static form
Methods “typename.FunctionName(
args)”
WHY IS STRING.JOIN
STATIC?
CONVERTING BYTES
TO/FROM STRINGS
BIT
CONVERTE
R DOES
NOT
WORK ON
STRINGS?!
e = "\u00C4 \uD802\u0033 \u00AE"; byte[] bytes= System.Text.Encoding.UTF8.GetBytes(value);
ystem.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.Get
Bytes()
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
concatenatio
concatenatio == Equality != Inequality
n and
n
assignment
They have a Length
property
Strings
They support indexing
are Like using an integer index
Arrays
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
String be changed after
they've been created
Immutabil Methods and C#
ity 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
• Likea safe and powerful version of
the C function sprintf().
• String.Format()
String Formatting
Formatting with String
interpolation
The Null Literal
• Thenull 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
QUERIE
S
Strings implement IEnumerable

This means you


Strings can loop
implement through the
“IEnumerable” 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