C++



Arrays Lesson 06: Arrays and Strings C# in 21 Days page 228 ->

Microsoft ref:

C# Matrices Part1

An array is a collection of variables of one particular type.

Each item in the array is accessed by an index, which is just a number that indicates the position

where the object is stored in the array.

We declare an array eg: int[] ag. // Declaration Square brackets means array.

This means that ag is an array variable (actually a reference to the eventual array) of integers.

Although a variable has been so far created, we have not assigned any memory to hold out 5 integers. ie it has not been initialized,

We can now assign data to our array ie initialize our array using new. ie

ag = new int[5]; // Initialization.

We can do this on one line as below: Try it.

int[]ag = new int[5]; // Declaration and Initialization

new has initialized our elements to 0. So to access an array element use ag[]

eg to access the 1st element use

Console.WriteLine(ag[0]);

If we wish to initialize our array use:

int[] ag = new int[5] { 1, 7, 5, 9, 3 };

The above works but actually there is no need for the 5 now.ie

int[] ag = new int[] { 1, 7, 5, 9, 3 };

Print out the first element age[0]:

Exercise : 1. Use a for loop to print them out.

2. Use a for each loop See later in this manual) to print them out.

0x00000000024D3350 05 00 00 00 ....

0x00000000024D3354 00 00 00 00 ....

0x00000000024D3358 01 00 00 00 ....

0x00000000024D335C 07 00 00 00 ....

0x00000000024D3360 05 00 00 00 ....

0x00000000024D3364 09 00 00 00 ....

0x00000000024D3368 03 00 00 00 ....

Arrays are reference types ie they are stored indirectly in memory.

If you want to see these elements in memory for yourself open a Watch window (Debug, Windows, Watch) and while the program is running (ie single-step) look for & age[0] ie the address of the 1st element.

Class exercise:

1. Use a loop (inside a) to print them out.

2. Make an array of integers eg. { 1, 7, 5, 9, 3 } as above and use a for loop to find the largest value. Hint: set max = age[0] and compare each value with this and swap as necessary.

3. Optional: Use the above to sort the array.

Hint 1: You would need a loop inside a loop.

Hint 2: The start position of the inside loop would need to be variable eg

for (int j = i; j < 5; j++ )

(Recall the exercise 2 on page 7 Lesson 2 for this particular concept).

A Two-Dimensional Array

We can declare our array as

int[,] age;

and initialize as

age = new int[2,4]; or in one step as

int[,] age = new int[2,4];

and print the 1st element:

Console.WriteLine(age[0,0]);

If we wished to initialize with our values (rather than the 0’s as above) :

int[,] age = new int[2, 4] { { 1, 3, 5, 9 }, { 2, 4, 6, 8 } };

The 2,4 could be omitted indeed we could have:

int[,] age = { { 1, 3, 5, 9 }, { 2, 4, 6, 8 } };

Now Console.WriteLine(age[0,0]);

Note how or array is actually stored in memory:

0x0000000002645E28 01 00 00 00

0x0000000002645E2C 03 00 00 00 1st row. 1 3 5 9

0x0000000002645E30 05 00 00 00

0x0000000002645E34 09 00 00 00

0x0000000002645E38 02 00 00 00

0x0000000002645E3C 04 00 00 00 2nd row. 2 4 6 8

0x0000000002645E40 06 00 00 00

0x0000000002645E44 08 00 00 00

Exercise:

1. Initialize two 2x2 matrices called m1 and m2 and add the elements together.

+ =

int[,] m1 = { { 1, 2 }, { 3, 4 } };

int[,] m2 = etc

int[,] m3 = new int[2,2];

Place the result in the new matrix m3.

2. Repeat the above using a loop inside another loop.

To Pass an Array to a Function C# Matrices Part2:

using System;

class test

{

static void Main()

{

int[,] age = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };

DoIt(age);

Console.ReadLine() ;

}

static void DoIt(int [,] age)

{

Console.WriteLine(age[0,0]); // Just the first element atm.

}

}

Passing by reference implies that if an array is passed to a function and then the function could change the array, it will be changed permanently ie:

Console.WriteLine(age[0,0]);

Console.ReadLine() ;

}

static void DoIt(int [,] age)

{

age[0, 0] = 9;

}

}

Exercise: We previously added together two 2x2 arrays m1 and m2.

Place the addition code in a function called MatAdd and pass the arrays to be added along with another array to hold the result.

(You could also make a function called initialize to initialize the values.)

Print the result in Main() (Or write another function called print to do that.)

As well as passing matrices to the function you might work out how to return the matrix m3 from the function – and then print it.

Using C#’s built in functions.

To Sort an Array

using System;

class test

{

static void Main()

{

int[] age = { 7, 1, 5, 9, 3 } ;

Array.Sort(age) ;

Console.WriteLine(age[0]) ;

Console.ReadLine() ;

}

}

Reverse

Array.Reverse(age) ;

(Useful after sort if we wish to sort in descending order.)

Length of an Array (number of elements)

Console.WriteLine(age.Length) ;

The length of a 2x2 array is 4 for example.

Rank of an Array (Number of dimensions – sort of)

Console.WriteLine(age.Rank) ;

GetUpperBound

Console.WriteLine(age.GetUpperBound(0)) ;

.

GetUpperBound is useful to iterate through the whole array eg

for (i=0;i address -> data) ie it is an object.

o Put a break point, Run and Add a watch for st1 and &st1 (the address of st1).

The actual memory looks something like this:

Strings of the string type are immutable ie we can’t change them as they stand in memory

We can’t add or change any characters in memory.

If and when a string is altered, a new string is created and the old one is discarded as we will now discuss.

The memory actually looks like this:

So if a string cannot be changed eg st1[0] = 'a'; how is a concatenation like the below performed?

using System;

class test

{

static void Main()

{

string st1 = "house";

st1 = st1 + "boat";

Console.WriteLine(st1);

Console.ReadLine();

}

}

Ans: A new string is created. The address to which st1 refers to is changed ie the reference is changed.

st1 originally points to the string "house" but when the string is concatenated it is then placed at a new address to which st1 will now point.

ie st1 now points to "houseboat" is at a different location. "house" is then lost in memory and ready for garbage collection.

o Single-step and watch st1.

… but after this line is executed…

Note that you do not use the new operator to create a string object.

To access any single character : Use square brackets.

string st1 = "house";

Console.WriteLine(st1[0]);

or use Char

Escape Characters use the backslash (\)

Console.WriteLine("house\nboat");

What if we actually wanted to print the backslash \? eg "C\eds\docs\user\temp"

Then we need to escape each backslash ie "C\\eds\\docs\\user\\temp"

This is a bit tedious so we can now use "@C\eds\docs\user\temp"

Try them.

Use \t for tab etc.

Comparing Strings

Console.WriteLine(pare("house","house"));

or Console.WriteLine(st1==st2); //Case sensitive

-1 or 1 would result if they were not equal.

When do we get a 1. When do we get a -1?

Length Property (It’s a property so no parentheses)

string s = "Hello World" ;

Console.WriteLine(s.Length) ;

Methods (Have got parentheses)

Insert

using System;

class test

{

public static void Main()

{

string s = "Goodbye World" ;

s = s.Insert(8, "Cruel ") ;

Console.WriteLine(s) ;

Console.ReadLine() ;

}

}

Trim

Removes leading and trailing spaces.

string s = " Hello World " ;

Console.WriteLine(s.Length) ;

s = s.Trim() ;

Console.WriteLine(s) ;

Console.WriteLine(s.Length) ;

IndexOf

Finds one string inside another.

string s = "xxxedxx" ;

Console.WriteLine(s.IndexOf("ed")) ;

IndexOf returns -1 if not found

Exercise: Use a While loop to find all of the positions of ed in

string stXML = "xxxedxxxxedxxxedx"

Substring

Extracts one string from another.

string s = "HipHopRadio" ;

Console.WriteLine(s.Substring(3,3)) ;

What is the effect of leaving off the 2nd parameter?

eg Console.WriteLine(s.Substring(3)) ;

Exercise 1. "abc.123" Extract the first 3 characters and the last 3 characters,

2. Extract the surname eg from this string string fullName = "Jack Robinson";

(This should work for any name.)

Replace

Replaces one string with another.

string s = "HipHopRadio" ;

s=s.Replace("Hop","pie") ;

Console.WriteLine(s) ;

Console.ReadLine() ;

Remove

Removes a certain number of characters.

string s = "HipHopRadio" ;

s=s.Remove(3,3) ;

ToUpper

Converts to upper case.

string s = "HipHopRadio" ;

s=s.ToUpper() ;

ToLower

Converts all to lower case.

An Array of Strings

string[] st1 = {"house","boat"};

Console.WriteLine(st1[0]);

Exercise 1: Print the a in boat.

Exercise 2: Pass the array of strings to a printStrings function to print them.

Join concatenates the elements of an array into one string.

using System;

class test

{

public static void Main()

{

string[] words = {"ed","jo","al"};

string s = string.Join("",words) ;

Console.WriteLine(s) ;

Console.ReadLine() ;

}

}

Split does the opposite

using System;

class test

{

public static void Main()

{

string s = "ed jo al" ;

string[] words = s.Split(' ') ;

Console.WriteLine(words[0]) ;

Console.ReadLine() ;

}

}

Class exercises:

Exercise 1 Take this string stXML = “ed;

Extract the data (“ed”). It this must be a general procedure for extract any data eg “joe” between the and tags,

Hint: Find the position of and first.

Exercise 2

Using the following string: string [] strs = {"XYZ.233","AXB.123",""CAB.456"}};

Write code to

1. Sort the strings. Hint: Take a look at previous note: To Sort an Array

2. For the exercise, swap just the first two strings.

3. Find the string which is lexographically smaller ie comes first in the alphabet.

It should of course be "AXB.123".

4. Place the string you found in 3. at the start ie you should have:

{"AXB.123", "XYZ.233", "CAB.456"}

5. Optional. Write code to sort the strings from scratch.

ie you should have: {"AXB.123", "CAB.456", "XYZ.233"}

You will need a loop inside a loop.

6. Find the position of ALL occurrences of “ed” in “xxxxxedxxxxxedxxxxxedx”

Hint 1: IndexOf()takes a second parameter which indicates the starting position of the search. Use a loop.

eg pos = st.IndexOf(s, pos) s is what you’re searching for.

pos is the start position. st is the above string.

Hint 2:. Don’t keep searching at the same position! Move it on one ie pos+1.

7. Take this string

stXML = "ed>joe";

Use a loop to extract the data . ed and joe.

Exercise:

We are given a CSV (comma delimited file) file: IBM,ICL,DAVY,USG

Print out the individual tickers ie

IBM

ICL

DAVY

USG

One method might be: Remove the first string ie IBM (and the comma) (recall that to do this we must first look for the comma) and then from this truncated string extract the ICL etc.

This may be a job for Regex (see later.) Best: Use Split!

Formatting Strings

The same formatting effects can be achieved by either of these 3 methods:

WriteLine, Format and ToString.

eg to truncate 1234.563 to two decimal places:

using 3 methods:

using System;

class test

{

public static void Main()

{

double num = 1234.563;

string s;

Console.WriteLine("{0:F2}",num) ;

s = string.Format("{0:F2}",num) ;

Console.WriteLine(s) ;

s = num.ToString("F2") ;

Console.WriteLine(s) ;

Console.ReadLine() ;

}

}

Note of course that Format and WriteLine require a placeholder, 0 in this case as well.

(Recall that the placeholder can be numbered 0,1,… as we have already seen eg. "{0:F2}""{1:F2}" etc.)

Using ToString we can specify the integer bit and decimal places:

double num = 12.34 ;

string s ;

s = num.ToString("000.000") ;

Console.WriteLine(s) ;

Note the difference between using # and 0:

s = num.ToString("#00.00#") ;

Exponential

double num = 12.34;

s = num.ToString("E3") ;

Currency

s = num.ToString("C3") ;

Positive and Negative Numbers

can be formatted differently.

double num = 12.34 ;

string s;

s = num.ToString(".#;-.##;'0'") ;

Console.WriteLine(s) ;

o eg try :

double num = -12.34 ;

double num = 0 ;

Date Time

DateTime dt = DateTime.Now;

string s;

s = dt.ToString("ddd MMM yyyy");

Console.WriteLine(s) ;

o Try

dd MMMM yy

To Convert from a String to a Number page 63 Ess C#

int i;

i = (int)st1; // won’t work…

…but this will:

string st1 = "123";

int i = int.Parse(st1);

Console.WriteLine(i);

But if when using Parse the string is not numeric it causes an exception: ie a run-time error.

So we must proceed with caution. If we are not sure use TryParse.

TryParse is False if not successful

using System;

class test

{

static void Main()

{

int i;

string st1 = "123"; // -> 123

Console.WriteLine( int.TryParse(st1, out i));

Console.WriteLine(i);

Console.ReadLine();

}

}

using System;

class test

{

static void Main()

{

string st1 = "hh";

int i; // i = 0 if not successful.

Console.WriteLine(int.TryParse(st1, out i));

Console.WriteLine(i);

Console.ReadLine();

}

}

StringBuilder C# in 21 Days page 407

StringBuilder strings are mutable cf. string strings..

The string s that we have seen so far have been immutable eg we can read a character but we cannot change a single character in the string.

string s = "Hello";

Console.WriteLine(s[0]) ;

s[0] = ‘B’; //Not possible!

..but using StringBuilder:

using System;

using System.Text;

StringBuilder s = new StringBuilder("Hello");

s[0] = 'B';

Console.WriteLine(s[0]) ;

StringBuilder’s methods are mainly concerned with modifying strings. eg

Append

StringBuilder s = new StringBuilder("Hello");

s.Append(" World");

Console.WriteLine(s) ;

Insert

Remove

Replace

ToString Converts to a fixed length string.

Further exercises: (For java but StringBuilder is the same)

Try them – even though they have got solutions.!

Regex Regex is used the find patterns in strings.

eg is this a valid UK email l:-> ed@una.co.uk ? (It is!)

To Find Text: eg This code finds if .com occurs in test@. It does of course.

using System;

using System.Text.RegularExpressions; // This namespace is required for Regex

class Program

{

static void Main()

{

string stEmail = "test@"; // Test this string

Regex rgx = new Regex(".com");

Boolean b = rgx.IsMatch(stEmail); //IsMatch is a property of the regex object.

Console.WriteLine(b); // True : .com IS in the email address.

Console.ReadLine();

}

}

Firstly using the above we have found .com in our email but note that the .com could be anywhere in the string. Try this.

eg string stEmail = "test@.comtest ";

Ultimately we might want to to test whether the whole email address is valid eg ed@ ie text then @ then text then .com - or how about ed@una.co.uk ?

Before looking at these patterns in detail:

More general searching with Regex:

Regex is more useful for looking at more general patterns eg rather than look for any particular characters eg .com we might want to know if any alphabetical character exists.

Arrays (yet to be included)

No ititialization

int[,] age = new int[2, 4] { { 1, 3, 5, 9 }, { 2, 4, 6, 8 } };

leave out indices:

Leave out “sugar”.

Initialization to zeros. Bit silly cause it’s done automatically (above).

-----------------------

Arrays don’t seem to be as important as they used to be. Rather we seem to use Generic Lists or Vectors (see later) these days.

The int indicates that what’s inside the array is integers.

This notation -just to make a simple array might appear cumbersome but we need to learn it.

Try it.

Note that counting starts from zero. ie ag[0] = 1, ag[1] = 3, ag[2] = 5, ag[3] = 7, ag[4] = 9. There are 5 elements in total. There is no ag[5]

But indeed we could just say:

int[] ag = { 1, 7, 5, 9, 3 };

whereby the missing new int[] bit has been described as “syntactic sugar” ie unnecessary!.

After our array is initialized we can see how the elements 1, 7, 5, 9, 3 are stored in memory. They are stored in “little-endian” eg

00 00 00 01 is stored in memory as

01 00 00 00 ie with the LSB (least significant byte) stored on the left.

Now copy this address into a memory Window (Debug, Windows, Memory ) and you should see the memory displayed as shown above.

[pic]

address of the array elements.

If we try &ag in our Watch window then we will not get the array but a value which is the address of the actual array.

If we look at that address then we will finally see our array – well our array with a bit of extra stuff at the start - a header giving the number of elements and the rank etc.

[pic]

When you declare a local variable, you are declaring the variable on the stack. Therefore a value type's value will be on the stack. A reference type's reference will be on the stack, and the object instance is still on the heap.

Try it.

Try it.

Try it.

Try it.

1 3 5 9

2 4 6 8

To view the above memory 1st find &age using Watch.

[pic]

Using this address in the memory window find the address of our array.

[pic]

Once again- this is the address 02645e08 of the array (ie a reference to the array) – not the actual array. We must then use this address to eventually (almost – it has a header as well) to find our array.

[pic]

The array!

We could also use the foreach statement to access all of the elements thus:

foreach (int el in age)

Console.WriteLine(el);

The elements of the 2-D array are printed out sequentially.

1+1=2 etc.

2 5

5 8

1 3

2 4

1 2

3 4

Nice way to print out our 2x2 array::

Console.WriteLine("{0} {1}", m3[0, 0], m3[0, 1]);

Console.WriteLine("{0} {1}", m3[1, 0], m3[1, 1]);

An array is always passed to a function by reference. An array is an object.

The reference is passed.

Strictly we should not use the same name for the variable

age with the function.

We could call it ag for example.

If we modify an element inside the method…

...then the value is permanently changed.

o Single-step and view the Locals window.

Sort is a static function - ie it does not use an object.

You might use this to print the contents:

foreach (int el in age)

Console.WriteLine(el);

We will see later how we could also use an interface if we wished to sort in reverse order.

The first dimension is the zeroth.

Remember that arrays are zero-based.

o Single-step and view the local window to view the two arrays.

o The 0 says to start copying at the first element of the destination array.

(In this instance make sure that the destination array age1 is big enough.)

The alternative to creating an array of structures would be to create them individually:

part p0 = new part();

p0.i = …

part p1= new part();

p1.i = …

part p2= new part();

p2.i = …

etc.

An array of objects of type part.

o Note the notation used to access the individual values.

Use a string type to hold the company name.

1 2 3 4

5 6 7

2 rows of various sized columns.

new must be used for each new array ie for each new row.

o Note the double bracket notation.

This is the best definitive reference.

Instead of string we could use String which is an alias.

string is a class. st1 is an object of that class.

This is the memory address 0x03c6ecc4 which holds the address 0x012ab754 of the actual location of the string.

At this address is the actual string.

The bytes are written backwards!

This address contains an address!

At this address is the actual string.

(In reality, these bytes are hex Unicode bytes - not characters.)

[pic]

[pic]

[pic]

(There is no 00 terminating byte as there is in C++. Also strings are objects – not simply contiguous memory locations as in C++.)

&st1 contains the address of the address of the string ie a reference type!

The address of the string (backwards).

Actually the string is a bit further on in memory– after a header giving the string length etc. After itis an object which is located here which contains the characters.

…st1 points to "house".

Before this line is executed…

… but now st1 points (indirectly) to "houseboat".

ie st1 is now a different address.

Take care when we set a reference to a string eg string st2 = st1 and then change the string st1. The reference st2 still points to the original string! eg Console.WriteLine(st2) ;

But we cannot write (ie add/replace) a single character to a string eg st1[0] = ‘x’; will not work – try it - because they are fixed in memory. If we need to modify the actual string then we need a StringBuilder string (see later).

When \n is embedded in a string, a new line is produced.

Use an @ in front to print the string literally ie its a verbatim string or a string literal.

Don’t forget the double equal sign for comparison.

For full list of methods see :



[pic]

Itellisense provides not only suggestions for the method but help on them as well.

TrimEnd() and TrimStart() remove the spaces from the end and start of the string respectively.

Note the first position is 0.

To stop the loop note that While returns 0 if not found.

Extract 3 characters.

Remember that the first position is 0 so that 3 indicates the fourth character.

3 characters.

Start position.

st1 is now an array containing strings.

The array of course is 0-based. st1[0] is the first element in the array - the first row.

st1[0][0] would give the first element of the first row ie h in this case.

Compare this with the notation for a jagged array – which is what an array of strings is!

Exercise: Write code to sort these strings. Hint: Write code to “bring the largest to the top”. Then make this the first element. Then use a loop inside a loop. Hint write code to swap two strings first.

The string separator in this case is "".

Also try " " here for example.

Split splits the string into a new array.

o A space is used here to determine where the string is split. This can of course be changed.

F means fixed point (ie decimal)

The 2 means 2 decimal places.

1

(Whereas Format and ToString produce a new string, WriteLine only writes it to the screen.)

2

3

# means nothing will be printed if nothing is there. Change it to 0 to see the effect. 0 means if nothing is there a 0 is printed.

E means 10.

3 means 3 decimal places.

3 means 3 decimal places.

There are 3 distinct formatting instructions,

If +ve then one dec place.

If '0' then 0.

If -ve then two dec places.

If '0' then 0.

mmm (small letters) is for minutes.

Converts a string to int.

Not numeric!

Indicates we are converting to int.

See also Convert.

Although string has this immutable limitation, in practice it is used more often than StringBuilder.

StringBuilder is faster.

Also think of StringBuilder as a utility. At the end of the day if we need to print it we would finally convert it to a string using ToString().

o Include System.Text; as well.

This does an implicit conversion using

Console.WriteLine(s[0].ToString()) ;

See C# in 21 Days

page 408

At the end of the day we need to convert our StringBuilder strings to “ordinary” strings – ie of the String class using ToString()!

We here create a Regex object rgx.

We pass the search string to its constructor.

(Note also that it only finds the first occurrence of .com at the moment.)

To Replace Text:

eg Replace .com in test@ with .nz -> test@test.nz

static void Main()

{

string stEmail = "test@"; // Test this string

Regex rgx = new Regex(".com");

string stOut = rgx.Replace(stEmail, ".nz"); // A new string!

Console.WriteLine(stOut); // True : .com is in the email address.

Console.ReadLine();

}

(There are other ways of doing this eg rgx.Pattern = ".com") etc.)

int[,] age = new int[2, 4];

int[,] age = new int[,] { { 1, 3, 5, 9 }, { 2, 4, 6, 8 } };

int[,] age = { { 1, 3, 5, 9 }, { 2, 4, 6, 8 } };

int[,] age = new int[,] { { 0, 0, 0, 0 }, { 0, 0, 0, 0 } };

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download