Presentation is loading. Please wait.

Presentation is loading. Please wait.

IS 350 Strings and Dates. Slide 2 Objectives Understand character-encoding systems and use the Char data type Use the String data type Call members of.

Similar presentations


Presentation on theme: "IS 350 Strings and Dates. Slide 2 Objectives Understand character-encoding systems and use the Char data type Use the String data type Call members of."— Presentation transcript:

1 IS 350 Strings and Dates

2 Slide 2 Objectives Understand character-encoding systems and use the Char data type Use the String data type Call members of the String class to manipulate textual data Work with the System.DateTime data type 2

3 Slide 3 Objectives (continued) Perform arithmetic operations on dates Use the TimeSpan data type to work with time intervals Use the DateTimePicker control Use the Timer control to fire events at regular intervals 3

4 Slide 4 Introduction to Character Encodings The English character set is relatively small Letters, digits, and a few special characters International character sets are more complex German has umlauts French has grave accents Many other diacritical marks exist Some languages have entirely unique character sets 4

5 Slide 5 The ASCII Character Set Early computers used different character sets making data communication between computers difficult or impossible ASCII was created in 1961 to supply a standard character set shared among computers An encoding scheme is a way of uniquely representing every character in a language with a unique binary value ASCII is but one encoding scheme 5

6 Slide 6 The Unicode Character Set ASCII cannot effectively represent the characters of international languages Unicode is an international character set, which stores a character in an unsigned 2-byte value Each unique character is called a code point 65,536 characters (code points) are possible The first 128 code points store ASCII characters The second 128 code points store special characters The remaining code points store symbols and diacritical marks 6

7 Slide 7 Introduction to the Char Data Type The Char data type stores a Unicode character in one 16-bit (2-byte) value The same syntax is used to declare a Char as any other data type Example to declare two Char variables: Dim LetterA, Result As Char 7

8 Slide 8 Conversions to the Char Data Type The System.Convert.ToChar() method converts a String or an Integer to a Char The Integer value corresponds to the Unicode code point Examples: LetterA = System.Convert.ToChar(65) LetterA = System.Convert.ToChar("A") 8

9 Slide 9 The Asc Function The Asc() function accepts a String or Char as an argument Asc returns the Integer code point of the first character in a string or the code point of the single character Examples: Dim Result As Integer Result = Asc("A") ' 65 Result = Asc("But this is a string") ' 66 9

10 Slide 10 The Chr Function The Chr() function converts a Unicode code point to a Char The argument contains the code point to convert The corresponding character ( Char ) is returned Example to convert an integer code point to a space character: Dim CurrentChar As Char = Chr(32) 10

11 Slide 11 Introduction to the String Data Type Many properties store consecutive characters called a string A string is a collection of characters having a data type of Char The Text property of a TextBox stores a string for example The String data type is a reference type 11

12 Slide 12 Declaring a String The syntax to declare a string is the same as the syntax to declare any other variable Multiple variables can be declared in the same statement Double quotation marks surround literal initialization values 12

13 Slide 13 Declaring a String (Example) Declare and initialize variables having a data type of String : Private Class frmMain Private Prefix As String Private FirstName, LastName As String Private CurrentName As String = _ "Joe Smith" ' procedures End Class 13

14 Slide 14 Strings and Assignment Statements Strings can be assigned just as numeric variables can be assigned Double quotation marks surround literal values Data types of both sides of an assignment statement must be the same Examples: Dim PersonName As String Dim CurrentName As String = "Joe Smith" PersonName = CurrentName PersonName = txtName.Text 14

15 Slide 15 Type Conversion Between Strings and Numeric Data Types Numeric data must often be converted to a String Call the ToString() method on any data type to convert a value to a string For numeric data types, a format specifier can be passed as an argument Example to convert a numeric value and format it as currency: Dim DataValue As Double = 1234.56 Dim FormattedOutputValue As String FormattedOutputValue = _ DataValue.ToString("C") 15

16 Slide 16 Converting Strings to Numeric Types The methods of the System.Convert class convert strings to numeric data types An error will occur if the value cannot be converted Example to convert the Text property of a text box: Dim IntegerDataValue As Integer IntegerDataValue = _ System.Convert.ToInt32(txtInput.Text) 16

17 Slide 17 String Operations Strings can be appended together (concatenated) The ampersand (&) operator is the concatenation operator Example: Dim FirstName As String = "John" Dim LastName As String = "Brown" Dim FullName As String FullName = FirstName & " " & LastName 17

18 Slide 18 String Concatenation 18

19 Slide 19 Control Characters and Special Characters Non-printable embedded characters are called control characters Defined control characters appear in the Microsoft.VisualBasic.ControlChars class Back constant embeds a backspace character CrLf constant embeds a carriage return, line feed sequence NullChar constant embeds a binary zero Quote constant embeds a double quotation mark Tab constant embeds a Tab character 19

20 Slide 20 Using Control Characters (example) Embed a carriage return in a string The string John and Brown will appear on separate lines Imports Microsoft.VisualBasic... txtOutput.Text = "John" & _ ControlChars.CrLf & "Brown" 20

21 Slide 21 Embedding Quotation Marks in Strings (example) Embed quotation marks in a string Example: Dim QuotedString As String = "The " & _ ControlChars.Quote & "Fox" & _ ControlChars.Quote & _ " Ran Fast. " Example output: The "Fox" Ran Fast. 21

22 Slide 22 Empty Strings The following statement creates a string with zero characters: EmptyString = "" The following statement creates a string that points to Nothing : EmptyString = Nothing 22

23 Slide 23 Creating an empty string 23

24 Slide 24 Working with Multiline Text Boxes Text appears on multiple lines when the MultiLine property is set to True Scroll bars appear based on the following settings for the ScrollBars property: None – no scroll bars appear Horizontal – horizontal scroll bar appears across the bottom of the text box Vertical – vertical scroll bar appears along the right side of the text box The WordWrap property defines whether lines wrap on word boundaries 24

25 Slide 25 the WordWrap property 25

26 Slide 26 String Manipulation Methods (Introduction) Determine the length of a string ( Length ) Convert the case of a string ( ToUpper, ToLower ) Work with parts of a string ( IndexOf, Substring, Insert, Remove, Replace ) Delete leading and trailing spaces ( TrimStart, TrimEnd, Trim ) 26

27 Slide 27 Determining the Length of a String ( Length ) Length() method of the String class returns the length of a string The method is one-based so a string with one character has a length of one An empty string has a length of zero Example (The string is 12 characters long): Dim FullName As String = "Mr. Ed Jones" Dim LengthOfString As Integer LengthOfString = FullName.Length() ' 12 27

28 Slide 28 Converting the Case of a String ( ToUpper, ToLower ) The ToUpper() method converts all characters to upper case The ToLower() method converts all characters to lower case 28

29 Slide 29 Converting the Case of a String (example) Dim CurrentString As String = _ "John Brown" Dim UpperString, LowerString As String UpperString = CurrentString.ToUpper() LowerString = CurrentString.ToLower() Example Output: JOHN BROWN john brown 29

30 Slide 30 The IndexOf Method (syntax) Public Function IndexOf(ByVal value As String) As Integer Public Function IndexOf(ByVal value As String, ByVal startIndex As Integer) As Integer Public Function IndexOf(ByVal value As String, ByVal startIndex As Integer, count As Integer) As Integer 30

31 Slide 31 The IndexOf Method (syntax continued) The IndexOf() method searches for a substring within a string IndexOf returns the character position of the first character in the string where the substring was found IndexOf returns -1 if the substring was not found First argument named value contains the substring Optional second argument contains the starting position in the string where the search begins Optional third argument contains the number of characters to search 31

32 Slide 32 The IndexOf Method (example) Search for a substring within a string Dim Position As Integer Dim States As String = _ "Arizona California Nevada" Position = States.IndexOf("California") ' 8 Position = States.IndexOf("California", 10) ' –1 Position = States.IndexOf("Arizona",0, 5) ' –1 32

33 Slide 33 The Substring Method (syntax) The Substring() method selects one or more characters from a string Public Function Substring(ByVal startIndex As Integer) As String Public Function Substring(ByVal startIndex As Integer, ByVal length As Integer) As String startIndex argument contains the character position where searching will begin length arguments contains the number of characters to search 33

34 Slide 34 The Substring Method (example) Select the numeric parts of a Social Security number Dim SSN As String = "555-12-3456" Dim Part1, Part2, Part3 As String Part1 = SSN.Substring(0, 3) ' 555 Part2 = SSN.Substring(4, 2) ' 12 Part3 = SSN.Substring(7, 4) ' 3456 34

35 Slide 35 Operation of the Substring method 35

36 Slide 36 The Insert Method (syntax) The Insert() method inserts one string into another string Public Function Insert(ByVal startIndex As Integer, ByVal value As String) As String startIndex argument contains the character position in the existing string where the new string will be inserted The value is 0-based value argument contains the string to be inserted 36

37 Slide 37 The Insert Method (example) Insert dashes into a Social Security number Dim SSN As String = "590123456" SSN = SSN.Insert(5, "-") SSN = SSN.Insert(3, "-") 37

38 Slide 38 Operation of the Insert method 38

39 Slide 39 The Remove Method The Remove() method deletes one or more characters from a string Public Function Remove(ByVal startIndex As Integer) As String Public Function Remove(ByVal startIndex As Integer, count As Integer) As String First method removes all characters from startIndex to the end of the string Second method removes count characters starting at startIndex 39

40 Slide 40 The Remove Method (example) Remove the area code from a telephone number Example: Dim Telephone As String = "702-555-1212" Dim TelephoneNoAreaCode As String TelephoneNoAreaCode = Telephone.Remove(0, 4) Example result: 555-1212 40

41 Slide 41 Operation of the Remove method 41

42 Slide 42 The Replace Method The Replace() method replaces one character with another character or one string pattern with another string pattern Public Function Replace(ByVal oldChar As Char, ByVal newChar As Char) As String Public Function Replace(ByVal oldValue As String, ByVal newValue As String) As String In the first method, the character in oldChar is replaced by newChar In the second method, the string in oldValue is replaced by the string in newValue 42

43 Slide 43 The Replace Method (example) Replace a space with no character (nothing) Dim InputString As String = "A B C D E" InputString = InputString.Replace(" ", "") 43

44 Slide 44 Deleting Leading or Trailing Spaces Three methods trim leading and trailing spaces TrimStart() removes leading spaces from a string TrimEnd() removes trailing spaces Trim() removes both leading and trailing spaces 44

45 Slide 45 Deleting Leading or Trailing Spaces (example) Trim a string: Dim InputString As String = _ " Joe Smith " Dim ResultString As String ResultString = InputString.TrimStart ' "Joe Smith " ResultString = InputString.TrimEnd ' " Joe Smith" ResultString = InputString.Trim ' "Joe Smith" 45

46 Slide 46 Introduction to Dates The System.DateTime data type is used with dates Two problems must be solved when working with dates Every calendar must define the "beginning of time" called the epoch Every calendar must increment time somehow 46

47 Slide 47 The Epoch Different computer systems represent the beginning of time differently UNIX uses January 1, 1970 as the beginning of time Windows uses January 1, 0001 as the epoch 47

48 Slide 48 Representing a Point in Time Using the Gregorian calendar, time is incremented daily Fractional parts of a day are referred to as timekeeping In UNIX, time is incremented in milliseconds Windows increments time in 100 nanosecond units called ticks 48

49 Slide 49 The System.DateTime Data Type The DataTime data type is a structure so it is a value type Its members perform operations on dates The syntax to declare a DateTime structure is the same as the syntax to declare any other variable Pound signs surround literal date values 49

50 Slide 50 Declaring a DateTime Variable (example) The following statements declare and initialize variables having the DateTime data type: Dim CurrentDate As DateTime Dim PastDate, FutureDate As DateTime Dim InitializedDate As DateTime = #7/4/2010# 50

51 Slide 51 Members of the DateTime Structure The MinValue and MaxValue properties store the minimum and maximum possible date values Example: Dim MaximumDate As DateTime = _ System.DateTime.MaxValue Dim MinimumDate As DateTime = _ System.DateTime.MinValue 51

52 Slide 52 Members of the DateTime Structure (continued) Now method gets the current date and time Today method gets the current date The time value is 00:00:00 Examples: Dim CurrentDateAndTime As DateTime = _ System.DateTime.Now Dim CurrentDate As DateTime = _ System.DateTime.Today 52

53 Slide 53 Members of the DateTime Structure (continued) Day, Month, and Year properties return the day of the month, month of the year, and year Hour, Minute, and Second properties return time elements having the same name DayOfWeek property returns the day of the week 0 = Sunday and 6 = Saturday DayOfYear property returns an Integer containing day of the year The first day of the year is 1 53

54 Slide 54 Members of the DateTime Structure (continued) IsDaylightSavingTime property accepts an argument containing a date Method returns True if daylight savings time is in effect IsLeapYear() method accepts one Integer argument containing a year Method returns True if the year is a leap year 54

55 Slide 55 Converting Dates to Strings The ToString() method converts a date to a string 7/4/2010 12:17:54 AM The ToLongDateString() method converts a date to a string using the system's long date format Sunday, July 4, 2010 The ToShortDateString() method converts a date to a string using the system's short date format 7/4/2010 Use the Control Panel to set the system's date formats 55

56 Slide 56 Converting Dates to Strings (continued) The ToLongTimeString() method converts a date to a string using the system's long time format 12:17:54 AM The ToShortTimeString() method converts a date to a string using the system's short time format 12:17 AM 56

57 Slide 57 Performing Calculations on Dates AddHours, AddMintutes, AddSeconds add time intervals to a date AddYears, AddMonths, AddDays add date intervals to a day Use negative values to subtract date or time intervals DaysInMonth returns the number of days in a particular month 57

58 Slide 58 Performing Calculations on Dates (example) Call the date arithmetic methods Dim Current As DateTime = Today ' July 4, 2010 12:17:54 PM Current = Current.AddDays(1.0) ' July 5, 2010 12:17:54 PM Current = Current.AddHours(2.5) ' July 5, 2010 2:47:54 PM Current = Current.AddYears(-1) ' July 5, 2009 2:47:54 PM 58

59 Slide 59 Introduction to the TimeSpan Structure The TimeSpan structure represents a time interval The number of whole days, minutes, and seconds in the interval are stored in the Days, Minutes and Seconds properties 121 seconds would be 2 Minutes and 1 Second The total fractional days is stored in the TotalDays, TotalMinutes, and TotalSeconds properties 59

60 Slide 60 The TimeSpan Structure (examples) Dim Span1 As New TimeSpan(1, 1, 1) Dim Span2 As New TimeSpan(2, 2, 2) Dim Span3 As TimeSpan = Span2 + Span1 Console.WriteLine(Span3.Hours.ToString) ' 3 Console.WriteLine(Span3.Minutes.ToString) ' 3 Console.WriteLine(Span3.Seconds.ToString) ' 3 Console.WriteLine(Span3.TotalHours.ToString) ' 3.0508333 Console.WriteLine(Span3.TotalMinutes.ToString) ' 183.05 Console.WriteLine(Span3.TotalSeconds.ToString) ' 10983 60

61 Slide 61 Adding and Subtracting Dates The DateTime data type has 2 date arithmetic methods Add accepts a TimeSpan and returns a new date Subtract has two forms One form subtracts a TimeSpan and returns a Date Another form subtracts a Date and returns a TimeSpan 61

62 Slide 62 Adding Dates The Add() method adds a TimeSpan to a DateTime Example: Dim Current As DateTime = #7/4/2010 12:30:00 PM# Dim Span As New TimeSpan(24, 0, 0) Current = Current.Add(Span) ' 7/5/2010 12:30:00 PM 62

63 Slide 63 Subtracting Dates (example) Dim DateIn1 As DateTime = #7/4/2010 12:30:00 PM# Dim DateIn2 As DateTime = #7/5/2010 12:30:00 PM# Dim DateOut As DateTime Dim SpanIn As New TimeSpan(24, 0, 0) Dim SpanOut As TimeSpan DateOut = DateIn2.Subtract(SpanIn) ' 7/4/2010 12:30:00 PM SpanOut = DateIn2.Subtract(DateIn1) ' 1 day (24 hours) 63

64 Slide 64 The DateTimePicker Control The DateTimePicker control gives the end user an easy way to select a date using a visual calendar Arrows let the end user select a month Select a year using a drop-down list Select a date from the drop-down calendar to set the date and close the calendar 64

65 Slide 65 DateTimePicker control instance with calendar exposed 65

66 Slide 66 The DateTimePicker Control (members) Font property defines the font appearing in the control instance Format property defines how the data in the control instance appears to the end user MaxDate and MinDate properties define the minimum and maximum user selectable dates Value property contains the selected date 66

67 Slide 67 The Timer Control The Timer control fires a Tick event at regular intervals The Interval property defines the timer's interval The unit of measure is milliseconds 1000 milliseconds is 1 second The Tick event only fires if the Enabled property is True 67

68 Slide 68 The Timer Control (example) Display a simple clock Private Sub tmrClock_Tick( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles tmrClock.Tick lblClock.Text = _ System.DateTime.Now.ToLongTimeString() End Sub 68

69 Slide 69 Chapter Summary An encoding scheme is a way of uniquely representing every character in a language with a unique binary value ASCII and Unicode are two common encoding schemes The Char data type stores a Unicode character The String data type stores a collection of characters Numerous methods of the String class manipulate strings 69

70 Slide 70 Chapter Summary (continued) The System.DateTime structure stores a date and time Numerous properties get date information Methods perform arithmetic on dates The System.TimeSpan structure stores a date and time interval (elapsed time) The DateTimePicker control allows the end user to select a date between a date range The Timer control fires events at regular intervals 70


Download ppt "IS 350 Strings and Dates. Slide 2 Objectives Understand character-encoding systems and use the Char data type Use the String data type Call members of."

Similar presentations


Ads by Google