SlideShare a Scribd company logo
Array  String String Builder
Arrays Arrays are collections of several elements of the same  type E.g. 100 integers, 20 strings, 125 students, 12 dates, etc. Single name is given to the entire array But each element is accessed separately  Any element of a n array  can be accessed just as quickly as any other element Arrays are  homogeneous  each item  (sometimes called  element )  has the  same type that type  must  be specified at declaration Items in an array are numbered (e.g. 1 st , 3 rd , or 105 th ) those are called  index  or  subscript numbering  starts with 0 we have to use the index value to refer an element in an array
Arrays Arrays are  fixed-length  entities. Length   property gives the length of the array. static Array.Resize  resizes an array. It takes two arguments—the array to be resized and the new length. Arrays are  reference types —what we typically think of as an array is actually a reference to an array object. The elements of an array can be either value types or reference types. For example, every element of an  int  array is an  int  value, and every element of a  string  array is a reference to a  string  object. We access an array element specifying array’s name and element’s  index  (position in the array). Index starts at  0 (zero) . CLR performs bounds checking for you and throws  IndexOutOfRangeException .
Examples See Array.cs int[] counter = new int[9]; char[] letters = new char[12]; string[] strArray = new string[5];  Dice[] diceArray = new Dice[4]; int[] c;  c = new int[12]; 0  0  0  0  0  0  0  0  0 0  0  0  0  0  0  0  0  0   0  0  0 null  null  null  null  null null  null  null  null  0  1  2  3  4  5  6  7  8 counter 0  1  2  3  4  5  6  7  8  9  10  11  letters 0  1  2  3  4 strArray 0  1  2  3  diceArray
How to reach a single array element specify the index value within square brackets after the vector/array name var_name  [ index_expr ] the value of  index expression must be between 0 and (array size – 1) .NET performs bounds checking for you and throws  IndexOutOfRangeException . Examples int[] nums = new int(9); nums[5] = 102; nums[0] = nums[5]*2-1; nums[nums[5]/20-3] = 55; nums[10] = 5;  // exception nums 102 203 55 0  1  2  3  4  5  6  7  8
Array Element Access for (int i = 0; i < counter.Length; i++)  Console.WriteLine(&quot;{0} {1}&quot;, i, counter[i]); int[] array = new int[10]; for (int i = 0; i < array.Length; i++) array[i] = 2 + 2 * i; Dice[] diceArray = new Dice[4]; for (int i = 0; i < diceArray.Length; i++) { diceArray[i] = new Dice(6); diceArray[i].Roll();   }
Array Initializers int[] array = {32, 27, 64, 18, 95, 14, 90, 70, 60}; 32   27   64  18  95  14  90  70  60 0  1  2  3  4  5  6  7  8 array
Passing Arrays and Array Elements to Methods as Parameters To pass an array argument to a method, specify the name of the array without any brackets. For a method to receive an array reference through a method call, the method’s parameter list must specify an array parameter. When an argument to a method is an entire array or an individual array element of a reference type, the called method receives a copy of the reference. When an argument to a method is an individual array element of a value type, the called method receives a copy of the element’s value. To pass an individual array element to a method, use the indexed name of the array as an argument in the method call. Example:  ArrayParameter.cs
foreach The  foreach   statement iterates through the elements of an entire array or collection. foreach ( type  identifier   in   arrayName  )  { <s tatement1> ; ... < statementN> ; } type  and  identifier  are the type and name (e.g.  int number ) of  the  iteration variable . The  type  of the iteration variable must match the  type  of the elements in the array. The iteration variable represents successive values in the array on successive iterations of the  foreach  statement.
Example:  foreach.cs int[] array = {87, 68, 94, 100, 83, 78, 85, 91, 76}; int total = 0; // add each element's value to total foreach ( int number in array ) total += number;
Implicitly Typed Variables C# provides a new feature—called  implicitly typed local variables —that enables the compiler to infer a local variable’s type based on the type of the variable’s initializer. To distinguish such an initialization from a simple assignment statement, the  var  keyword is used in place of the variable’s type. You can use local type inference with control variables in the header of a for or foreach statement. if myArray is an array of ints, the following foreach statement headers are equivalent: foreach  ( int  number  in  myArray) foreach  ( var  number  in  myArray)
System.String string  is the alias for  System.String A string is an object of class string in the System namespace representing a series of characters. These characters can be uppercase letters, lowercase letters, digits and various  special characters . Character constants are established according to the  Unicode character set . String  is a reference type. The keyword null represents a null, not an empty string (which is a string object that is of length 0 and contains no characters). The  String.Empty  should be used if you need a string with no characters.
StringConstructor.cs Class string provides 8 constructors. Below is the use of 3 constructors: Assign a string literal to string reference originalString. The  string  constructor can take a  char  array and two  int  arguments for starting position and length. Copy a reference to another  string  literal. The  string  constructor can take a character array as an argument. The  string  constructor can take as arguments a character and an  int  specifying the number of times to repeat that character in the  string .
String Properties Property  Length  allows you to determine the number of characters in a string. The string  indexer  treats a string as an array of chars and returns each character at a specific position in the string. As with arrays, the first element of a string is considered to be at position 0.  Attempting to access a character that is outside a string’s bounds i.e., an index less than 0 or an index greater than or equal to the string’s length) results in an  IndexOutOfRangeException .  The string method CopyTo copies a specified number of characters from a string into a char array.  StringMethods.cs
Comparing Strings Method  Equals  tests any two objects for equality (i.e., checks whether the objects contain identical contents). The string class’s  Equals  method uses a  lexicographical comparison —comparing the integer Unicode values of character in each string. The overloaded string equality operator  ==  also uses a lexicographical comparison to compare two strings. String comparisons are case-sensitive. Method   CompareTo   returns:   0 if the strings are equal   A negative value if the calling string is less than the argument string   A positive value if the calling string is greater than the argument.   Example:  StringCompare.cs
Searching Strings StartWith   and   EndWith string s = “started”; if ( s.StartsWith(“st”) ) … if ( s.EndsWith(“ed”) ) … IndexOf locates the first occurrence of a  character  or  substring  in a string and returns its index, or -1 if it is not found. LastIndexOf like  IndexOf , but searches from the end of the string. IndexOfAny  and  LastIndexOfAny take an array of characters as the first argument and return the index of the first occurrence of any of the characters in the array.
Substring  and  Concat Substring  methods which create a new string by copying part of an existing string. s.Substr(20); s.Substr(0, 6); Like the  + operator , the static method  Concat  of class string concatenates two strings and returns a new string. string strNew = String.Concat(str1, str2); String strNew = str1 + str2; String[] words = sentence. Split (' '); string2 = string1. Replace (‘e’, ‘E’); string2 = string1. ToUpper ()  and  string2 = string1. ToLower () string2 = string1. Trim (); Examples:  StringMethods2.cs
StringBuilder Objects of class  string  are immutable. Class  StringBuilder  is used to create and manipulate dynamic string information—i.e., mutable strings. StringBuilder  is much more efficient for working with large numbers of strings than creating individual immutable strings  .
StringBuilder  constructors The no-parameter  StringBuilder  constructor creates an empty  StringBuilder  with a default capacity of 16 characters. Given a single int argument, the  StringBuilder  constructor creates an empty  StringBuilder  that has the initial capacity specified in the int argument. Given a single string argument, the  StringBuilder  constructor creates a  StringBuilder  containing the characters of the string argument. Its initial capacity is the smallest power of two greater than or equal to the number of characters in the argument string, with a minimum of 16.
StringBuilder  features Class  StringBuilder  provides the  Length  and  Capacity  properties. Method  EnsureCapacity  doubles the  StringBuilder  instance’s current capacity. If this doubled value is greater than the value that the programmer wishes to ensure, that value becomes the new capacity. Otherwise,  EnsureCapacity  alters the capacity to make it equal to the requested number. When a  StringBuilder  exceeds its capacity, it grows in the same manner as if method  EnsureCapacity  had been called. If  Length  is set to a value less than the number of characters in the  StringBuilder  , the contents of the  StringBuilder  are truncated.
Append  and  AppendFormat Class StringBuilder provides 19 overloaded  Append  methods that allow various types of values to be added to the end of a StringBuilder. The Framework Class Library provides versions for each of the simple types and for character arrays, strings and objects. Examples:  StringBuilderAppend.cs AppendFormat  converts a string to a specified format, then appends it to the StringBuilder. Examples:  StringBuilderAppendFormat.cs
Append  and  AppendFormat Formats have the form {X[,Y][:FormatString]}. X is the number of the argument to be formatted, counting from zero. Y is an optional argument, which can be positive or negative, indicating how many characters should be in the result. A positive integer aligns the string to the right; a negative integer aligns it to the left. The optional FormatString applies a particular format to the argument—currency, decimal or scientific, among others.   One version of AppendFormat takes a string specifying the format and an array of objects to serve as the arguments to the format string.
Other Methods of  StringBuilder Insert  inserts its second argument into the  StringBuilder  in front of the character in the position specified by the first argument.  Remove takes two arguments—the index at which to begin deletion and the number of characters to delete. Replace  searches for a specified string or character and substitutes another string or character in its place.
char  Methods char is an alias for the  struct   Char . Char method  IsDigit  determines whether a  character is defined as a digit. IsLetter  determines whether a character is a letter. IsLetterOrDigit  determines whether a character is a letter or a digit. IsLower  determines whether a character is a lowercase letter. IsUpper  determines whether a character is an uppercase letter. ToUpper  returns a character’s uppercase equivalent, or the original argument if there is no uppercase equivalent.
char  Methods ToLower  returns a character lowercase equivalent, or the original argument if there is no lowercase equivalent. IsPunctuation  determines whether a character is a punctuation mark, such as &quot;!&quot;, &quot;:&quot; or &quot;)&quot;. IsSymbol  determines whether a character is a symbol, such as &quot;+&quot;, &quot;=&quot; or &quot;^&quot;. Static method  IsWhiteSpace . Public instance methods:  ToString ,  Equals , and  CompareTo .
Multidimensional Arrays 2-dimensional rectangular array: An array with  m  rows and  n  columns is called an  m-by-n   array . Every element in array a is identified by an array-access expression of the form a[  row,   column  ]; A two-by-two rectangular array  b  can be declared and initialized as follows: int[ , ] b = {  {  1, 2  } ,  {  3, 4  }  }; The initializer values are grouped by row in braces.
Jagged Arrays A  jagged array  is a one-dimensional array whose elements are one-dimensional arrays. The lengths of the rows in the array need not be the same. A jagged array with three rows of different lengths could be declared and initialized as follows: int[][] jagged = { new int[] { 1, 2 },   new int[] { 3 },   new int[] { 4, 5, 6 } };
Multidimensional Arrays A rectangular array can be created with an array-creation expression: int [ , ] b; b =  new int [  3 ,  4  ]; A jagged array cannot be completely created with a single array-creation expression. Each one-dimensional array must be initialized separately. A jagged array can be created as follows: int [][] c; c =  new int [  2  ][ ];  // create 2 rows c[  0  ] =  new int [  5  ];  // create 5 columns for row 0 c[  1  ] =  new int [  3  ];  // create 3 columns for row 1
Searching an array We can search for one occurrence, return true/false or the index of occurrence Search  the  array  starting from the beginning S top searching when match is found We can search and count the number of occurrences and return count Search entire array  Similar to one occurrence search, but do not stop after first occurrence We can search for many occurrences, but return occurrences in another array rather than count In all these cases, we search the array sequentially starting from the beginning This type of search is called  “sequential search”
Counting search static int CountMatches(string[] a, string s) {   int count = 0; for (int k = 0; k < a.Length; k++) { if (a[k] == s) { count++; } } return count; } How can we change this code to return the index of the first occurrence?  see next slide
One occurrence search static int FirstMatch(string[] a, string s) { for (int k = 0; k < a.Length; k++) { if (a[k] == s) { return k; } } return -1; } Does not search the entire array if one match is found good for efficiency purposes How could you modify this to return true/false?
Collecting search Collect the occurrences of a string in another vector and return it static string[] Collect(string[] inVector, string find)
Binary search Alternative to sequential search for sorted vectors If a vector is  sorted  we can use the sorted property to eliminate half of the vector elements with one comparison What number  (between 1 and 100)  do we guess first in  number guessing game ? Idea of creating program to do binary search Check the middle element If it has the searched value, then you’re done! If not,  eliminate half of the  elements of the vector search the rest using the same idea continue until match is found or there is no match how could you understand that there is no match? let’s develop the algorithm on an example we need two index values, low and high, for the search space Array.BinarySearch
Sorting an Array One of the fundamental operations in Computer Science Given a randomly ordered array, sort it ascending descending Array.Sort
Array Exercise Consider the following example: generate a random number [1..6] and count the number of occurrences of all outcomes (1, 2, 3, 4, 5, 6) Repeat this 6000 times and display statistics
Variable-length argument lists Variable-length argument lists  allow you to create methods that receive an arbitrary number of arguments. The necessary  params  modifier can occur only in the last entry of the parameter list.  Example:  ParamArrayTest.cs
Command-line Arguments You can pass  command-line arguments   to an application by including a parameter of type  string[]  in the parameter list of  Main . By convention, this parameter is named  args . The execution environment passes the command-line argu­ments as an array to the application’s Main method. The number of arguments passed from the command line is obtained by accessing the array’s  Length  property. Command-line arguments are separated by white space, not commas. Example:  VarargsTest.cs
enum An  enumerated type  is a  value  type that defines a set of symbolic name and value pairs. For example: enum type identifying a single color: public enum Color { White,  // Assigned a value of 0 Red,  // Assigned a value of 1 Green,  // Assigned a value of 2 Blue,  // Assigned a value of 3 Orange,  // Assigned a value of 4 } Other examples: days/months, cards types, states in a game, etc. etc. Let’s see example code:  enum.cs
System.Enum  methods public static bool IsDefined(Type enumType, object value); public static object Parse(Type enumType, string value); public static object Parse(Type enumType, string value,  bool ignoreCase); public static string GetName(Type enumType, object value); public static string[] GetNames(Type enumType); public static Array GetValues(Type enumType); public int CompareTo(object target); public static string Format(Type enumType, object value,    string format); public override string ToString(); public static object ToObject(Type enumType, int value);  // many overloads

More Related Content

What's hot (19)

PPTX
Python Datatypes by SujithKumar
Sujith Kumar
 
PPTX
Regular expressions in Python
Sujith Kumar
 
PDF
Datatypes in python
eShikshak
 
PDF
Python list
Prof. Dr. K. Adisesha
 
PPTX
Basic data structures in python
Celine George
 
PDF
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
PDF
Python data handling notes
Prof. Dr. K. Adisesha
 
PDF
Arrays in python
moazamali28
 
PDF
Strings in python
Prabhakaran V M
 
PPTX
Iteration
Pooja B S
 
PPTX
Data types in python
RaginiJain21
 
PPT
Strings In OOP(Object oriented programming)
Danial Virk
 
PPTX
Parts of python programming language
Megha V
 
PDF
1. python
PRASHANT OJHA
 
PDF
List,tuple,dictionary
nitamhaske
 
KEY
Programming with Python - Week 3
Ahmet Bulut
 
PDF
Python data handling
Prof. Dr. K. Adisesha
 
Python Datatypes by SujithKumar
Sujith Kumar
 
Regular expressions in Python
Sujith Kumar
 
Datatypes in python
eShikshak
 
Basic data structures in python
Celine George
 
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
Python data handling notes
Prof. Dr. K. Adisesha
 
Arrays in python
moazamali28
 
Strings in python
Prabhakaran V M
 
Iteration
Pooja B S
 
Data types in python
RaginiJain21
 
Strings In OOP(Object oriented programming)
Danial Virk
 
Parts of python programming language
Megha V
 
1. python
PRASHANT OJHA
 
List,tuple,dictionary
nitamhaske
 
Programming with Python - Week 3
Ahmet Bulut
 
Python data handling
Prof. Dr. K. Adisesha
 

Viewers also liked (19)

PPTX
Control flow statements in java
yugandhar vadlamudi
 
PPT
4.1 sequentioal search
Krish_ver2
 
PPTX
Java SE 8
Murali Pachiyappan
 
PPTX
Byte array to hex string transformer
Rahul Kumar
 
PDF
5 2. string processing
웅식 전
 
PDF
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
IDES Editor
 
PPT
algorithm
kokilabe
 
PPTX
TypeScript by Howard
LearningTech
 
PDF
Multi string PV array
NIT MEGHALAYA
 
PDF
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
PPTX
Nomenclature of Organic Compounds (IUPAC)
Lexter Supnet
 
PPTX
Epics and User Stories
Manish Agrawal, CSP®
 
PPT
Iupac nomenclature
Ashwani Kumar
 
PPTX
자바로 배우는 자료구조
중선 곽
 
PPTX
Iupac nomenclature class 11 CBSE-organic chemistry some basic principles and ...
ritik
 
PDF
프로그래머가 알아야 하는 메모리 관리 기법
중선 곽
 
PPTX
ORGANIC CHEMISTRY FOR CLASS XI CBSE
kapde1970
 
PPTX
Arrays in java
bhavesh prakash
 
Control flow statements in java
yugandhar vadlamudi
 
4.1 sequentioal search
Krish_ver2
 
Byte array to hex string transformer
Rahul Kumar
 
5 2. string processing
웅식 전
 
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
IDES Editor
 
algorithm
kokilabe
 
TypeScript by Howard
LearningTech
 
Multi string PV array
NIT MEGHALAYA
 
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
Nomenclature of Organic Compounds (IUPAC)
Lexter Supnet
 
Epics and User Stories
Manish Agrawal, CSP®
 
Iupac nomenclature
Ashwani Kumar
 
자바로 배우는 자료구조
중선 곽
 
Iupac nomenclature class 11 CBSE-organic chemistry some basic principles and ...
ritik
 
프로그래머가 알아야 하는 메모리 관리 기법
중선 곽
 
ORGANIC CHEMISTRY FOR CLASS XI CBSE
kapde1970
 
Arrays in java
bhavesh prakash
 
Ad

Similar to Strings Arrays (20)

PPTX
Arrays in programming
TaseerRao
 
PPT
2 arrays
trixiacruz
 
PPT
Ap Power Point Chpt6
dplunkett
 
PPTX
Java
JahnaviBhagat
 
PDF
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
PPT
07 Arrays
maznabili
 
PPTX
stringstringbuilderstringbuffer-190830060142.pptx
ssuser99ca78
 
PPT
Chapter 9 - Characters and Strings
Eduardo Bergavera
 
PPT
Java căn bản - Chapter9
Vince Vo
 
PPTX
Module 7 : Arrays
Prem Kumar Badri
 
PPTX
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
PPT
M C6java7
mbruggen
 
DOCX
Array assignment
Ahmad Kamal
 
PPT
slidlecturlecturlecturlecturlecturlecturlecturlectures06.ppt
KierenReynolds3
 
PPT
Arrays in Java Programming Language slides
ssuser5d6130
 
PPT
Chap09
Terry Yoast
 
PPTX
STRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVA
pkavithascs
 
PPT
9781439035665 ppt ch09
Terry Yoast
 
PPS
String and string buffer
kamal kotecha
 
Arrays in programming
TaseerRao
 
2 arrays
trixiacruz
 
Ap Power Point Chpt6
dplunkett
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
07 Arrays
maznabili
 
stringstringbuilderstringbuffer-190830060142.pptx
ssuser99ca78
 
Chapter 9 - Characters and Strings
Eduardo Bergavera
 
Java căn bản - Chapter9
Vince Vo
 
Module 7 : Arrays
Prem Kumar Badri
 
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
M C6java7
mbruggen
 
Array assignment
Ahmad Kamal
 
slidlecturlecturlecturlecturlecturlecturlecturlectures06.ppt
KierenReynolds3
 
Arrays in Java Programming Language slides
ssuser5d6130
 
Chap09
Terry Yoast
 
STRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVA
pkavithascs
 
9781439035665 ppt ch09
Terry Yoast
 
String and string buffer
kamal kotecha
 
Ad

More from phanleson (20)

PDF
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
PPT
Firewall - Network Defense in Depth Firewalls
phanleson
 
PPT
Mobile Security - Wireless hacking
phanleson
 
PPT
Authentication in wireless - Security in Wireless Protocols
phanleson
 
PPT
E-Commerce Security - Application attacks - Server Attacks
phanleson
 
PPT
Hacking web applications
phanleson
 
PPTX
HBase In Action - Chapter 04: HBase table design
phanleson
 
PPT
HBase In Action - Chapter 10 - Operations
phanleson
 
PPT
Hbase in action - Chapter 09: Deploying HBase
phanleson
 
PPTX
Learning spark ch11 - Machine Learning with MLlib
phanleson
 
PPTX
Learning spark ch10 - Spark Streaming
phanleson
 
PPTX
Learning spark ch09 - Spark SQL
phanleson
 
PPT
Learning spark ch07 - Running on a Cluster
phanleson
 
PPTX
Learning spark ch06 - Advanced Spark Programming
phanleson
 
PPTX
Learning spark ch05 - Loading and Saving Your Data
phanleson
 
PPTX
Learning spark ch04 - Working with Key/Value Pairs
phanleson
 
PPTX
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
PPT
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
phanleson
 
PPT
Lecture 1 - Getting to know XML
phanleson
 
PPTX
Lecture 4 - Adding XTHML for the Web
phanleson
 
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
Firewall - Network Defense in Depth Firewalls
phanleson
 
Mobile Security - Wireless hacking
phanleson
 
Authentication in wireless - Security in Wireless Protocols
phanleson
 
E-Commerce Security - Application attacks - Server Attacks
phanleson
 
Hacking web applications
phanleson
 
HBase In Action - Chapter 04: HBase table design
phanleson
 
HBase In Action - Chapter 10 - Operations
phanleson
 
Hbase in action - Chapter 09: Deploying HBase
phanleson
 
Learning spark ch11 - Machine Learning with MLlib
phanleson
 
Learning spark ch10 - Spark Streaming
phanleson
 
Learning spark ch09 - Spark SQL
phanleson
 
Learning spark ch07 - Running on a Cluster
phanleson
 
Learning spark ch06 - Advanced Spark Programming
phanleson
 
Learning spark ch05 - Loading and Saving Your Data
phanleson
 
Learning spark ch04 - Working with Key/Value Pairs
phanleson
 
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
phanleson
 
Lecture 1 - Getting to know XML
phanleson
 
Lecture 4 - Adding XTHML for the Web
phanleson
 

Recently uploaded (20)

PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Digital Circuits, important subject in CS
contactparinay1
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 

Strings Arrays

  • 1. Array String String Builder
  • 2. Arrays Arrays are collections of several elements of the same type E.g. 100 integers, 20 strings, 125 students, 12 dates, etc. Single name is given to the entire array But each element is accessed separately Any element of a n array can be accessed just as quickly as any other element Arrays are homogeneous each item (sometimes called element ) has the same type that type must be specified at declaration Items in an array are numbered (e.g. 1 st , 3 rd , or 105 th ) those are called index or subscript numbering starts with 0 we have to use the index value to refer an element in an array
  • 3. Arrays Arrays are fixed-length entities. Length property gives the length of the array. static Array.Resize resizes an array. It takes two arguments—the array to be resized and the new length. Arrays are reference types —what we typically think of as an array is actually a reference to an array object. The elements of an array can be either value types or reference types. For example, every element of an int array is an int value, and every element of a string array is a reference to a string object. We access an array element specifying array’s name and element’s index (position in the array). Index starts at 0 (zero) . CLR performs bounds checking for you and throws IndexOutOfRangeException .
  • 4. Examples See Array.cs int[] counter = new int[9]; char[] letters = new char[12]; string[] strArray = new string[5]; Dice[] diceArray = new Dice[4]; int[] c; c = new int[12]; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 null null null null null null null null null 0 1 2 3 4 5 6 7 8 counter 0 1 2 3 4 5 6 7 8 9 10 11 letters 0 1 2 3 4 strArray 0 1 2 3 diceArray
  • 5. How to reach a single array element specify the index value within square brackets after the vector/array name var_name [ index_expr ] the value of index expression must be between 0 and (array size – 1) .NET performs bounds checking for you and throws IndexOutOfRangeException . Examples int[] nums = new int(9); nums[5] = 102; nums[0] = nums[5]*2-1; nums[nums[5]/20-3] = 55; nums[10] = 5; // exception nums 102 203 55 0 1 2 3 4 5 6 7 8
  • 6. Array Element Access for (int i = 0; i < counter.Length; i++) Console.WriteLine(&quot;{0} {1}&quot;, i, counter[i]); int[] array = new int[10]; for (int i = 0; i < array.Length; i++) array[i] = 2 + 2 * i; Dice[] diceArray = new Dice[4]; for (int i = 0; i < diceArray.Length; i++) { diceArray[i] = new Dice(6); diceArray[i].Roll(); }
  • 7. Array Initializers int[] array = {32, 27, 64, 18, 95, 14, 90, 70, 60}; 32 27 64 18 95 14 90 70 60 0 1 2 3 4 5 6 7 8 array
  • 8. Passing Arrays and Array Elements to Methods as Parameters To pass an array argument to a method, specify the name of the array without any brackets. For a method to receive an array reference through a method call, the method’s parameter list must specify an array parameter. When an argument to a method is an entire array or an individual array element of a reference type, the called method receives a copy of the reference. When an argument to a method is an individual array element of a value type, the called method receives a copy of the element’s value. To pass an individual array element to a method, use the indexed name of the array as an argument in the method call. Example: ArrayParameter.cs
  • 9. foreach The foreach statement iterates through the elements of an entire array or collection. foreach ( type identifier in arrayName ) { <s tatement1> ; ... < statementN> ; } type and identifier are the type and name (e.g. int number ) of the iteration variable . The type of the iteration variable must match the type of the elements in the array. The iteration variable represents successive values in the array on successive iterations of the foreach statement.
  • 10. Example: foreach.cs int[] array = {87, 68, 94, 100, 83, 78, 85, 91, 76}; int total = 0; // add each element's value to total foreach ( int number in array ) total += number;
  • 11. Implicitly Typed Variables C# provides a new feature—called implicitly typed local variables —that enables the compiler to infer a local variable’s type based on the type of the variable’s initializer. To distinguish such an initialization from a simple assignment statement, the var keyword is used in place of the variable’s type. You can use local type inference with control variables in the header of a for or foreach statement. if myArray is an array of ints, the following foreach statement headers are equivalent: foreach ( int number in myArray) foreach ( var number in myArray)
  • 12. System.String string is the alias for System.String A string is an object of class string in the System namespace representing a series of characters. These characters can be uppercase letters, lowercase letters, digits and various special characters . Character constants are established according to the Unicode character set . String is a reference type. The keyword null represents a null, not an empty string (which is a string object that is of length 0 and contains no characters). The String.Empty should be used if you need a string with no characters.
  • 13. StringConstructor.cs Class string provides 8 constructors. Below is the use of 3 constructors: Assign a string literal to string reference originalString. The string constructor can take a char array and two int arguments for starting position and length. Copy a reference to another string literal. The string constructor can take a character array as an argument. The string constructor can take as arguments a character and an int specifying the number of times to repeat that character in the string .
  • 14. String Properties Property Length allows you to determine the number of characters in a string. The string indexer treats a string as an array of chars and returns each character at a specific position in the string. As with arrays, the first element of a string is considered to be at position 0. Attempting to access a character that is outside a string’s bounds i.e., an index less than 0 or an index greater than or equal to the string’s length) results in an IndexOutOfRangeException . The string method CopyTo copies a specified number of characters from a string into a char array. StringMethods.cs
  • 15. Comparing Strings Method Equals tests any two objects for equality (i.e., checks whether the objects contain identical contents). The string class’s Equals method uses a lexicographical comparison —comparing the integer Unicode values of character in each string. The overloaded string equality operator == also uses a lexicographical comparison to compare two strings. String comparisons are case-sensitive. Method CompareTo returns: 0 if the strings are equal A negative value if the calling string is less than the argument string A positive value if the calling string is greater than the argument. Example: StringCompare.cs
  • 16. Searching Strings StartWith and EndWith string s = “started”; if ( s.StartsWith(“st”) ) … if ( s.EndsWith(“ed”) ) … IndexOf locates the first occurrence of a character or substring in a string and returns its index, or -1 if it is not found. LastIndexOf like IndexOf , but searches from the end of the string. IndexOfAny and LastIndexOfAny take an array of characters as the first argument and return the index of the first occurrence of any of the characters in the array.
  • 17. Substring and Concat Substring methods which create a new string by copying part of an existing string. s.Substr(20); s.Substr(0, 6); Like the + operator , the static method Concat of class string concatenates two strings and returns a new string. string strNew = String.Concat(str1, str2); String strNew = str1 + str2; String[] words = sentence. Split (' '); string2 = string1. Replace (‘e’, ‘E’); string2 = string1. ToUpper () and string2 = string1. ToLower () string2 = string1. Trim (); Examples: StringMethods2.cs
  • 18. StringBuilder Objects of class string are immutable. Class StringBuilder is used to create and manipulate dynamic string information—i.e., mutable strings. StringBuilder is much more efficient for working with large numbers of strings than creating individual immutable strings .
  • 19. StringBuilder constructors The no-parameter StringBuilder constructor creates an empty StringBuilder with a default capacity of 16 characters. Given a single int argument, the StringBuilder constructor creates an empty StringBuilder that has the initial capacity specified in the int argument. Given a single string argument, the StringBuilder constructor creates a StringBuilder containing the characters of the string argument. Its initial capacity is the smallest power of two greater than or equal to the number of characters in the argument string, with a minimum of 16.
  • 20. StringBuilder features Class StringBuilder provides the Length and Capacity properties. Method EnsureCapacity doubles the StringBuilder instance’s current capacity. If this doubled value is greater than the value that the programmer wishes to ensure, that value becomes the new capacity. Otherwise, EnsureCapacity alters the capacity to make it equal to the requested number. When a StringBuilder exceeds its capacity, it grows in the same manner as if method EnsureCapacity had been called. If Length is set to a value less than the number of characters in the StringBuilder , the contents of the StringBuilder are truncated.
  • 21. Append and AppendFormat Class StringBuilder provides 19 overloaded Append methods that allow various types of values to be added to the end of a StringBuilder. The Framework Class Library provides versions for each of the simple types and for character arrays, strings and objects. Examples: StringBuilderAppend.cs AppendFormat converts a string to a specified format, then appends it to the StringBuilder. Examples: StringBuilderAppendFormat.cs
  • 22. Append and AppendFormat Formats have the form {X[,Y][:FormatString]}. X is the number of the argument to be formatted, counting from zero. Y is an optional argument, which can be positive or negative, indicating how many characters should be in the result. A positive integer aligns the string to the right; a negative integer aligns it to the left. The optional FormatString applies a particular format to the argument—currency, decimal or scientific, among others. One version of AppendFormat takes a string specifying the format and an array of objects to serve as the arguments to the format string.
  • 23. Other Methods of StringBuilder Insert inserts its second argument into the StringBuilder in front of the character in the position specified by the first argument. Remove takes two arguments—the index at which to begin deletion and the number of characters to delete. Replace searches for a specified string or character and substitutes another string or character in its place.
  • 24. char Methods char is an alias for the struct Char . Char method IsDigit determines whether a character is defined as a digit. IsLetter determines whether a character is a letter. IsLetterOrDigit determines whether a character is a letter or a digit. IsLower determines whether a character is a lowercase letter. IsUpper determines whether a character is an uppercase letter. ToUpper returns a character’s uppercase equivalent, or the original argument if there is no uppercase equivalent.
  • 25. char Methods ToLower returns a character lowercase equivalent, or the original argument if there is no lowercase equivalent. IsPunctuation determines whether a character is a punctuation mark, such as &quot;!&quot;, &quot;:&quot; or &quot;)&quot;. IsSymbol determines whether a character is a symbol, such as &quot;+&quot;, &quot;=&quot; or &quot;^&quot;. Static method IsWhiteSpace . Public instance methods: ToString , Equals , and CompareTo .
  • 26. Multidimensional Arrays 2-dimensional rectangular array: An array with m rows and n columns is called an m-by-n array . Every element in array a is identified by an array-access expression of the form a[  row,   column  ]; A two-by-two rectangular array b can be declared and initialized as follows: int[ , ] b = { { 1, 2 } , { 3, 4 } }; The initializer values are grouped by row in braces.
  • 27. Jagged Arrays A jagged array is a one-dimensional array whose elements are one-dimensional arrays. The lengths of the rows in the array need not be the same. A jagged array with three rows of different lengths could be declared and initialized as follows: int[][] jagged = { new int[] { 1, 2 }, new int[] { 3 }, new int[] { 4, 5, 6 } };
  • 28. Multidimensional Arrays A rectangular array can be created with an array-creation expression: int [ , ] b; b = new int [ 3 , 4 ]; A jagged array cannot be completely created with a single array-creation expression. Each one-dimensional array must be initialized separately. A jagged array can be created as follows: int [][] c; c = new int [ 2 ][ ]; // create 2 rows c[ 0 ] = new int [ 5 ]; // create 5 columns for row 0 c[ 1 ] = new int [ 3 ]; // create 3 columns for row 1
  • 29. Searching an array We can search for one occurrence, return true/false or the index of occurrence Search the array starting from the beginning S top searching when match is found We can search and count the number of occurrences and return count Search entire array Similar to one occurrence search, but do not stop after first occurrence We can search for many occurrences, but return occurrences in another array rather than count In all these cases, we search the array sequentially starting from the beginning This type of search is called “sequential search”
  • 30. Counting search static int CountMatches(string[] a, string s) { int count = 0; for (int k = 0; k < a.Length; k++) { if (a[k] == s) { count++; } } return count; } How can we change this code to return the index of the first occurrence? see next slide
  • 31. One occurrence search static int FirstMatch(string[] a, string s) { for (int k = 0; k < a.Length; k++) { if (a[k] == s) { return k; } } return -1; } Does not search the entire array if one match is found good for efficiency purposes How could you modify this to return true/false?
  • 32. Collecting search Collect the occurrences of a string in another vector and return it static string[] Collect(string[] inVector, string find)
  • 33. Binary search Alternative to sequential search for sorted vectors If a vector is sorted we can use the sorted property to eliminate half of the vector elements with one comparison What number (between 1 and 100) do we guess first in number guessing game ? Idea of creating program to do binary search Check the middle element If it has the searched value, then you’re done! If not, eliminate half of the elements of the vector search the rest using the same idea continue until match is found or there is no match how could you understand that there is no match? let’s develop the algorithm on an example we need two index values, low and high, for the search space Array.BinarySearch
  • 34. Sorting an Array One of the fundamental operations in Computer Science Given a randomly ordered array, sort it ascending descending Array.Sort
  • 35. Array Exercise Consider the following example: generate a random number [1..6] and count the number of occurrences of all outcomes (1, 2, 3, 4, 5, 6) Repeat this 6000 times and display statistics
  • 36. Variable-length argument lists Variable-length argument lists allow you to create methods that receive an arbitrary number of arguments. The necessary params modifier can occur only in the last entry of the parameter list. Example: ParamArrayTest.cs
  • 37. Command-line Arguments You can pass command-line arguments to an application by including a parameter of type string[] in the parameter list of Main . By convention, this parameter is named args . The execution environment passes the command-line argu­ments as an array to the application’s Main method. The number of arguments passed from the command line is obtained by accessing the array’s Length property. Command-line arguments are separated by white space, not commas. Example: VarargsTest.cs
  • 38. enum An enumerated type is a value type that defines a set of symbolic name and value pairs. For example: enum type identifying a single color: public enum Color { White, // Assigned a value of 0 Red, // Assigned a value of 1 Green, // Assigned a value of 2 Blue, // Assigned a value of 3 Orange, // Assigned a value of 4 } Other examples: days/months, cards types, states in a game, etc. etc. Let’s see example code: enum.cs
  • 39. System.Enum methods public static bool IsDefined(Type enumType, object value); public static object Parse(Type enumType, string value); public static object Parse(Type enumType, string value, bool ignoreCase); public static string GetName(Type enumType, object value); public static string[] GetNames(Type enumType); public static Array GetValues(Type enumType); public int CompareTo(object target); public static string Format(Type enumType, object value, string format); public override string ToString(); public static object ToObject(Type enumType, int value); // many overloads