BİL527 – Bilgisayar Programlama I Strings 1. Contents More on Variables – Type Conversions – Enumerations – Structs – Arrays – String Operations 2.

Slides:



Advertisements
Similar presentations
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
Advertisements

Strings in Java 1. strings in java are handled by two classes String &
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Neal Stublen C# Data Types Built-in Types  Integer Types byte, sbyte, short, ushort, int, uint, long, ulong  Floating Point Types.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 5 Types Types are the leaven of computer programming;
Sizes of simple data types sizeof(char) = 1 size(short) = 2 sizeof(int) = 4 size(long) = 8 sizeof(char) = 1 size(short) = 2 sizeof(int) = 2 size(long)
Computer Science 1620 Other Data Types. Quick Review: checklist for performing user input: 1) Be sure variable is declared 2) Prompt the user for input.
Constants. 2 Objectives Describe ways to create constants –const –readonly –enum.
Basic Elements of C++ Chapter 2.
Performing Simple Calculations with C# Svetlin Nakov Telerik Corporation
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Agenda Review User input Scanner Strong type checking Other flow-control structures switch break & continue Strings Arrays 2.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
Introduction to Classes and Objects (Through Ch 5) Dr. John P. Abraham Professor UTPA.
BİL528 – Bilgisayar Programlama II
1. 2 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decisions { class.
3. Declaring Value-Type Variables
C Tokens Identifiers Keywords Constants Operators Special symbols.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Chapter 2: Using Data.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
BIM313 – Advanced Programming Techniques Strings and Functions 1.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.
August 6, 2009 Data Types, Variables, and Arrays.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Types(1). Lecture 52 Type(1)  A type is a collection of values and operations on those values. Integer type  values..., -2, -1, 0, 1, 2,...  operations.
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 8 th Lecture Pavel Ježek
Performing Simple Calculations with C# Telerik Corporation
Weekly C-minar Week 0. Today: Steps of the compile Basic inclusion/syntax rules Low-cost containment Debugging.
CSci 162 Lecture 2 Martin van Bommel. Enumeration –process of listing all of the elements in the domain of a type Enumerated type –type defined via enumeration.
1.2 Primitive Data Types and Variables
Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:
Session 1 C# Basics.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 Enums (Chapter 4) To enumerate is: to name things one after another in a list Java has a type, called an enum, where a programmer specifies a finite.
Enum,Structure and Nullable Types Ashima Wadhwa. Enumerations, Enumerations, or enums, are used to group named constants similar to how they are used.
Pointers A pointer type variable holds the address of a data object or a function. A pointer can refer to an object of any one data type; it cannot refer.
Session 2 Operators, Decisions and Loops. Objectives Operators Casting data Decision marking structures Loops break, continue, return.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Expressions Version Topics Arithmetic expressions Conversions Operator precedence String class 2.
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
Variables and Expression COSC Fall 2014 Bridget Blodgett.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
Java Programming Language Lecture27- An Introduction.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Lecture 2 Computational Constructs Variables & Expressions Boolean Logic Conditionals: if & switch Branching & Looping Data Types & Type Conversion Structs,
Computing with C# and the .NET Framework
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Advanced Programming Behnam Hatami Fall 2017.
Advanced Programming in Java
Chapter 15 Pointers, Dynamic Data, and Reference Types
.Net Programming with C#
Chapter 15 Pointers, Dynamic Data, and Reference Types
SystemVerilog for Verification
C++ Programming Lecture 3 C++ Basics – Part I
Java Programming Language
Visual Programming COMP-315
Type Conversion It is a procedure of converting one data type values into another data type In C programming language we are having two types of type conversion.
Presentation transcript:

BİL527 – Bilgisayar Programlama I Strings 1

Contents More on Variables – Type Conversions – Enumerations – Structs – Arrays – String Operations 2

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

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

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

Implicit Type Conversions TypeCan Safely Be Converted To charushort, int, uint, long, ulong, float, double, decimal byteshort, ushort, int, uint, long, ulong, float, double, decimal sbyteshort, int, long, float, double, decimal shortint, long, float, double, decimal ushortint, uint, long, ulong, float, double, decimal intlong, float, double, decimal uintlong, ulong, float, double, decimal longfloat, double, decimal ulongfloat, double, decimal floatdouble - decimal- 6

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

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?)

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

Range Problem byte b; short s = 281; b = (byte) s; Console.WriteLine(“b = {0}, s = {1}”, b, s); 10 b = 25, s = doesn’t fit into the byte range! Amount of overflow from 256!

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

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

Complex Variable Types Enumerations (enum) Structures (struct) Arrays 13

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

enum Syntax Definition: enum {, … } 15

enum Syntax Declaring variables: ; Assigning values: =. ; 16

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

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

Advanced Topics on enum (2) You can change underlying integer values of some enumerations Unspecified values are automatically generated by incrementing last value enum Orientation {North=1, South, East=4, West=8} 19 North = 1, South = 2, East = 4, West = 8

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

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

Defining Structs struct { ; … } 22

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

Declaring a struct variable Syntax: ; Example: Route myRoute; myRoute.Orientation = Orientation.North; myRoute.Distance = 2.5; 24

Example route 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 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

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

Declaring Arrays Syntax: [] ; Example: – int[] myIntArray; – string[] myStringArray; In this declaration, only a reference without any elements is created 27

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

Accessing Array Elements arr[5] = 10; – 10 is assigned to the 6 th element of the array – Indexing starts from 0 (not 1) int num = arr[5]; – 6 th 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

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

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

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

String Operations (1) Concatenation – str = str1 + str2; Accessing a char at specified location – char ch = str[3]; // 4 th element is assigned to ch Getting the length – int size = str.Length; Getting all chars into a char array – char[] chars = str.ToCharArray(); 33

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

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

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 spaces string str = “This is a pencil”; string[] arr = str.Split(); foreach (string s in arr) { Console.WriteLine(s); } 36 This is a pencil

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

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