Docsity

Arrays and Strings in C#: Access, Initialization, and Manipulation, Slides of Advanced Algorithms

Partial preview of the text

Download Arrays and Strings in C#: Access, Initialization, and Manipulation and more Slides Advanced Algorithms in PDF only on Docsity!

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 an 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

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

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

nums (^203 )

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

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

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)

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.

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

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 Docsity.com

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.