Strings Arrays

39
Array String String Builder

Transcript of Strings Arrays

Page 1: Strings Arrays

Array String

String Builder

Page 2: Strings Arrays

ArraysArrays are collections of several elements of the same

typeE.g. 100 integers, 20 strings, 125 students, 12 dates, etc.Single name is given to the entire arrayBut each element is accessed separately Any element of an array can be accessed just as quickly as any

other elementArrays are homogeneous

each item (sometimes called element) has the same typethat type must be specified at declaration

Items in an array are numbered (e.g. 1st, 3rd, or 105th)those are called index or subscriptnumbering starts with 0we have to use the index value to refer an element in an array

Page 3: Strings Arrays

ArraysArrays 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.

Page 4: Strings Arrays

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 1 2 3 4 5 6 7 8

counter

0 0 0 0 0 0 0 0 0

0 1 2 3 4 5 6 7 8 9 10 11

letters

0 0 0 0 0 0 0 0 0 0 0 0

0 1 2 3 4

strArray

null null null null null

0 1 2 3

diceArray

null null null null

Page 5: Strings Arrays

How to reach a single array elementspecify the index value within square brackets after the

vector/array namevar_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.

Examplesint[] nums = new int(9);

nums[5] = 102;nums[0] = nums[5]*2-1;nums[nums[5]/20-3] = 55;

nums[10] = 5; // exception 0 1 2 3 4 5 6 7 8

nums

102203 55

Page 6: Strings Arrays

Array Element Access

for (int i = 0; i < counter.Length; i++) Console.WriteLine("{0} {1}", 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();

}

Page 7: Strings Arrays

Array Initializers

int[] array = {32, 27, 64, 18, 95, 14, 90, 70, 60};

0 1 2 3 4 5 6 7 8

array

32 27 64 18 95 14 90 70 60

Page 8: Strings Arrays

Passing Arrays and Array Elements to Methods as ParametersTo 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

Page 9: Strings Arrays

foreachThe foreach statement iterates through the elements of an

entire array or collection.

foreach (type identifier in arrayName ) {

<statement1>;...<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.

Page 10: Strings Arrays

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;

Page 11: Strings Arrays

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)

Page 12: Strings Arrays

System.Stringstring is the alias for System.StringA 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.

Page 13: Strings Arrays

1 // Fig. 18.1: StringConstructor.cs

2 // Demonstrating string class constructors.

3 using System;

4

5 class StringConstructor

6 {

7 public static void Main( string[] args )

8 {

9 // string initialization

10 char[] characterArray =

11 { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };

12 string originalString = "Welcome to C# programming!";

13 string string1 = originalString;

14 string string2 = new string( characterArray );

15 string string3 = new string( characterArray, 6, 3 );

16 string string4 = new string( 'C', 5 );

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.

Page 14: Strings Arrays

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

Page 15: Strings Arrays

Comparing StringsMethod 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

Page 16: Strings Arrays

Searching StringsStartWith and EndWith

string s = “started”;if ( s.StartsWith(“st”) )…

if ( s.EndsWith(“ed”) )…

IndexOflocates 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.

Page 17: Strings Arrays

Substring and ConcatSubstring 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

Page 18: Strings Arrays

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 .

Page 19: Strings Arrays

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.

Page 20: Strings Arrays

StringBuilder featuresClass 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.

Page 21: Strings Arrays

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

Page 22: Strings Arrays

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.

Page 23: Strings Arrays

Other Methods of StringBuilderInsert

inserts its second argument into the StringBuilder in front of the character in the position specified by the first argument.

Removetakes 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.

Page 24: Strings Arrays

char Methodschar 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.

Page 25: Strings Arrays

char MethodsToLower 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 "!", ":" or ")".IsSymbol determines whether a character is a symbol,

such as "+", "=" or "^".Static method IsWhiteSpace.Public instance methods: ToString, Equals, and

CompareTo.

Page 26: Strings Arrays

Multidimensional Arrays2-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.

Page 27: Strings Arrays

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 } };

Page 28: Strings Arrays

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 rowsc[ 0 ] = new int[ 5 ]; // create 5 columns for row 0c[ 1 ] = new int[ 3 ]; // create 3 columns for row 1

Page 29: Strings Arrays

Searching an arrayWe can search for one occurrence, return true/false or the

index of occurrenceSearch the array starting from the beginningStop searching when match is found

We can search and count the number of occurrences and return countSearch 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 beginningThis type of search is called “sequential search”

Page 30: Strings Arrays

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

Page 31: Strings Arrays

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?

Page 32: Strings Arrays

Collecting searchCollect the occurrences of a string in another vector and

return it

static string[] Collect(string[] inVector, string find)

Page 33: Strings Arrays

Binary searchAlternative to sequential search for sorted vectorsIf a vector is sorted we can use the sorted property to

eliminate half of the vector elements with one comparisonWhat number (between 1 and 100) do we guess first in number

guessing game?

Idea of creating program to do binary searchCheck 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 ideacontinue 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

Page 34: Strings Arrays

Sorting an ArrayOne of the fundamental operations in Computer

ScienceGiven a randomly ordered array, sort it

ascendingdescending

Array.Sort

Page 35: Strings Arrays

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

Page 36: Strings Arrays

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

Page 37: Strings Arrays

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

Page 38: Strings Arrays

enumAn 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

Page 39: Strings Arrays

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