BİL527 – Bilgisayar Programlama I

38
BİL527 – Bilgisayar Programlama I Strings 1

description

BİL527 – Bilgisayar Programlama I. Strings. Contents. More on Variables Type Conversions Enumerations Structs Arrays String Operations. Type Conversion. Examples string to int or int to string double to int (rounding operations) Implicit Conversions No data loss - PowerPoint PPT Presentation

Transcript of BİL527 – Bilgisayar Programlama I

Page 1: BİL527 – Bilgisayar Programlama I

BİL527 – Bilgisayar Programlama I

Strings

1

Page 2: BİL527 – Bilgisayar Programlama I

Contents

• More on Variables– Type Conversions– Enumerations– Structs– Arrays– String Operations

2

Page 3: BİL527 – Bilgisayar Programlama I

Type Conversion

• Examples– string to int or int to string– double to int (rounding operations)

• Implicit Conversions– No data loss– Trust in the compiler

• Explicit Conversions– Data may be lost– Approve the compiler

3

Page 4: BİL527 – Bilgisayar Programlama I

Implicit Conversions

• Implicit conversion requires no work on your part and no additional code.

• ushort and char types are effectively interchangeable, because both store a number between 0 and 65535.

4

Page 5: BİL527 – Bilgisayar Programlama I

Implicit Conversion Example

char ch = ‘a’;ushort num;num = ch;Console.WriteLine(“ch = {0}, num = {1}”, ch, num);

5

ch = a, num = 97

Page 6: BİL527 – Bilgisayar Programlama I

Implicit Type ConversionsType Can Safely Be Converted Tochar ushort, int, uint, long, ulong, float, double, decimalbyte short, ushort, int, uint, long, ulong, float, double, decimalsbyte short, int, long, float, double, decimalshort int, long, float, double, decimalushort int, uint, long, ulong, float, double, decimalint long, float, double, decimaluint long, ulong, float, double, decimallong float, double, decimalulong float, double, decimalfloat doubledouble -decimal -

6

Page 7: BİL527 – Bilgisayar Programlama I

Explicit Conversions

• Wide types can’t be converted to narrow types (e.g. conversion from short to byte)

• In such cases, compiler gives error:– Cannot implicitly convert type ‘short’ to ‘byte’. An explicit conversion

exists (are you missing a cast?)

• If you are sure that you really want to make the conversion, use the explicit conversion:– OK, I know you’ve warned me about doing this, but I’ll take

responsibility for what happens.

7

Page 8: BİL527 – Bilgisayar Programlama I

Example

byte b;short s = 7;b = s;Console.WriteLine(“b = {0}, s = {1}”, b, s);

8

Cannot implicitly convert type ‘short’ to ‘byte’. An explicit conversion exists(are you missing a cast?)

Page 9: BİL527 – Bilgisayar Programlama I

Solution

byte b;short s = 7;b = (byte) s;Console.WriteLine(“b = {0}, s = {1}”, b, s);

9

b = 7, s = 7

Page 10: BİL527 – Bilgisayar Programlama I

Range Problem

byte b;short s = 281;b = (byte) s;Console.WriteLine(“b = {0}, s = {1}”, b, s);

10

b = 25, s = 281

281 doesn’t fit into the byte range!

Amount of overflow from 256!

Page 11: BİL527 – Bilgisayar Programlama I

Explicit Conversions by “Convert”

• Another method to make explicit conversion is using the “Convert” methods:– int i = Convert.ToInt32(val)– float f = Convert.ToSingle(val)– double d = Convert.ToDouble(val)– string s = Convert.ToString(val)

• Here, val can be most types of variable.

11

Page 12: BİL527 – Bilgisayar Programlama I

A Note on Explicit Conversions

• If the explicit conversion is impossible, then your program is not compiled.– string s = “12.34”;– double d = (double)s;

• If the explicit conversion is possible but an error occurs in runtime, then an Exception occurs (i.e. your program crashes )– string s = “abcd”;– double d = Convert.ToDouble(s);

12

Page 13: BİL527 – Bilgisayar Programlama I

Complex Variable Types

• Enumerations (enum)• Structures (struct)• Arrays

13

Page 14: BİL527 – Bilgisayar Programlama I

Enumerations (enum)

• The type double is used to store fractional numbers• bool type is used to store true or false• In real life, there are other existences:– Orientation: North, South, East, West– Week Days: Monday, Tuesday, Wednesday, Thursday,

Friday, Saturday, Sunday– Months: January, February, …, December

• These types can be implemented by enumerations in C#.

14

Page 15: BİL527 – Bilgisayar Programlama I

enum Syntax

• Definition:enum <typeName>{ <value1>, <value2>, … <valueN>}

15

Page 16: BİL527 – Bilgisayar Programlama I

enum Syntax

• Declaring variables:<typeName> <varName>;

• Assigning values:<varName> = <typeName>.<value>;

16

Page 17: BİL527 – Bilgisayar Programlama I

enum Examplenamespace Ch05Ex02 { enum Orientation { North, South, East, West } class Program { static void Main(string[] args) { Orientation myDirection = Orientation.North; Console.WriteLine("myDirection = {0}", myDirection); } }}

17

Page 18: BİL527 – Bilgisayar Programlama I

Advanced Topics on enum (1)

• Each values in an enumeration are stored as integers, starting from 0 and incremented by 1– Console.WriteLine("{0} = {1}, {2} = {3}",

Orientation.North, (int)Orientation.North, Orientation.South, (int)Orientation.South);

18

North = 0, South = 1

Page 19: BİL527 – Bilgisayar Programlama I

Advanced Topics on enum (2)

• You can change underlying integer values of some enumerations

• Unspecified values are automatically generated by incrementing last valueenum Orientation {North=1, South, East=4, West=8}

19

North = 1, South = 2,East = 4, West = 8

Page 20: BİL527 – Bilgisayar Programlama I

Advanced Topics on enum (3)

• You can change the underlying type from the default type (int) to byte, short, and long (and their signed and unsigned versions)enum Orientation : byte {North, South, East, West}Console.WriteLine((byte)Orientation.North)

20

Page 21: BİL527 – Bilgisayar Programlama I

Structs

• Structs are data structures that are composed of several pieces of data, possibly of different types.– Student records (name, age, birth year, etc.)– Route (orientation, distance, etc.)

21

Page 22: BİL527 – Bilgisayar Programlama I

Defining Structs

struct <structName>{ <accessibility1> <type1> <name1>; <accessibility2> <type2> <name2>; …}

22

Page 23: BİL527 – Bilgisayar Programlama I

Example

struct Route{ public Orientation Direction; public double Distance;}

23

Page 24: BİL527 – Bilgisayar Programlama I

Declaring a struct variable

Syntax:<structName> <varName>;

Example:Route myRoute;myRoute.Orientation = Orientation.North;myRoute.Distance = 2.5;

24

Page 25: BİL527 – Bilgisayar Programlama I

Exampleroute myRoute;int myDirection = -1;double myDistance;Console.WriteLine("1) North\n2) South\n3) East\n4) West");do{ Console.WriteLine("Select a direction:"); myDirection = Convert.ToInt32(Console.ReadLine());} while (myDirection < 1 || myDirection > 4);Console.WriteLine("Input a distance:");myDistance = Convert.ToDouble(Console.ReadLine());myRoute.direction = (orientation)myDirection;myRoute.distance = myDistance;Console.WriteLine("myRoute specifies a direction of {0} and a " +"distance of {1}", myRoute.direction, myRoute.distance);

25

Page 26: BİL527 – Bilgisayar Programlama I

Arrays

• Use arrays to store large number of data of same type– int grade1, grade2, grade3, …;– int[] grades;

• Arrays make some operations simple– Think of the case where you want to initialize all

values to zero.

26

Page 27: BİL527 – Bilgisayar Programlama I

Declaring Arrays

• Syntax:<type>[] <name>;

• Example:– int[] myIntArray;– string[] myStringArray;

• In this declaration, only a reference without any elements is created

27

Page 28: BİL527 – Bilgisayar Programlama I

Initialization

• int[] arr = new int[5];– an array of 5 elements with default values (0 for

numbers)• int[] arr = {5, 9, 10, 2, 99};– an array of 5 elements with initial values

• int[] arr = new int[5] {5, 9, 10, 2, 99};– an array of 5 elements with initial values

• int[] arr = new int[10] {5, 9, 10, 2, 99};– an array of 10 elements but only first five of them are

initialized (the rest are initialized to the default value)

28

Page 29: BİL527 – Bilgisayar Programlama I

Accessing Array Elements

arr[5] = 10;– 10 is assigned to the 6th element of the array– Indexing starts from 0 (not 1)

int num = arr[5];– 6th element of the array is assigned to a variable

for (int i = 0; i < arr.Length; i++){ Console.WriteLine(arr[i]);}– All array elements are displayed on the screen.

29

Page 30: BİL527 – Bilgisayar Programlama I

Example

string[] friendNames = { "Robert Barwell", "Mike Parry", "Jeremy Beacock" };Console.WriteLine("Here are {0} of my friends:",friendNames.Length);for (int i = 0; i < friendNames.Length; i++){ Console.WriteLine(friendNames[i]);}

30

Page 31: BİL527 – Bilgisayar Programlama I

Same example with foreach

string[] friendNames = { "Robert Barwell", "Mike Parry", "Jeremy Beacock" };Console.WriteLine("Here are {0} of my friends:",friendNames.Length);foreach (string friendName in friendNames){ Console.WriteLine(friendName);}

31

Page 32: BİL527 – Bilgisayar Programlama I

Multidimensional Arrays

• int[,] mat = new int[5, 8];– Access as mat[i, j]

• int[,,] cube = new int[3, 5, 8];• int[,] mat = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};– Two-dimensional array of size 3x4 (3 rows, 4

columns)

32

Page 33: BİL527 – Bilgisayar Programlama I

String Operations (1)

• Concatenation– str = str1 + str2;

• Accessing a char at specified location– char ch = str[3]; // 4th element is assigned to ch

• Getting the length– int size = str.Length;

• Getting all chars into a char array– char[] chars = str.ToCharArray();

33

Page 34: BİL527 – Bilgisayar Programlama I

String Operations (2)

• Changing to upper or lower cases– str2 = str1.ToUpper();– str2 = str1.ToLower();• These methods doesn’t change str1!• If you want to change str1 itself, use this:

– str1 = str1.ToLower();

• Remove white spaces (space, tab, new line) at the beginning and at the end:– str2 = str1.Trim();

34

Page 35: BİL527 – Bilgisayar Programlama I

String Operations (3)

• Remove white spaces only at the beginning:– str2 = str1.TrimStart();

• Remove white spaces only at the end:– str2 = str1.TrimEnd();

• Substrings:– string str1 = “advanced”;– string str2 = str1.SubString(2, 3); // “van”– str2 = str1.SubString(2); // “vanced”

35

Page 36: BİL527 – Bilgisayar Programlama I

Split()• You can split a string using the Split() method• The Split() method returns a string array• It takes separator chars as a char array• If no parameters are supplied, it splits the string

according to the white spacesstring str = “This is a pencil”;string[] arr = str.Split();foreach (string s in arr){ Console.WriteLine(s);}

36

Thisisapencil

Page 37: BİL527 – Bilgisayar Programlama I

Using separators in Split()

string str = “1,2,3,4,5”;char[] separator = {‘,’};string[] arr = str.Split(separator);foreach (string s in arr){ Console.WriteLine(s);}

37

12345

Page 38: BİL527 – Bilgisayar Programlama I

Other String Operations

• Examine the following string methods by yourself:– CompareTo, Equals– Contains– StartsWith, EndsWith– IndexOf, IndexOfAny, LastIndexOf, LastIndexOfAny– PadLeft, PadRight– Remove– Replace

38