Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 The String and DateTime Data Types. Class 5: String & DateTime Understand the use of characters and strings Call members of the String class.

Similar presentations


Presentation on theme: "Chapter 5 The String and DateTime Data Types. Class 5: String & DateTime Understand the use of characters and strings Call members of the String class."— Presentation transcript:

1 Chapter 5 The String and DateTime Data Types

2 Class 5: String & DateTime Understand the use of characters and strings Call members of the String class to manipulate string data Work with the System.DateTime data type Use strings and dates to create a form letter

3 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

4 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

5 Introduction to the Char Data Type The Char data type stores a Unicode character in one 16-bit (2-byte) value Example to declare two Char variables: Dim LetterA, Result As Char

6 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")

7 The Asc Method The Asc method accepts a String or Char as an argument It 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("This is a string") ' 84

8 The Chr Method The Chr method converts a Unicode code point to a Char –The argument contains the code point to convert –The method returns the corresponding character ( Char ) Example to convert an integer code point to a space character: Dim CurrentChar As Char = Chr(32)

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

10 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 marksDouble quotation marks surround literal initialization values

11 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

12 Strings and Assignment Statements Strings can be assigned just as numeric variables can be assigned –Double quotation marks surround literal values –The 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

13 Strings and Type Conversion 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 value and format it as currency: Dim DataValue As Double = 1234.56 Dim FormattedOutputValue As String FormattedOutputValue = _ DataValue.ToString("C")

14 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 Dim SingleDataValue As Single IntegerDataValue = _ System.Convert.ToInt32(txtInput.Text) SingleDataValue = _ System.Convert.ToSingle(txtInput.Text)

15 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

16 Figure 5-2: String Concatenation

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

18 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"

19 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.

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

21 Figure 5-3: Creating an Empty String

22 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 – a horizontal scroll bar appears across the bottom of the text box –Vertical – a vertical scroll bar appears along the right side of the text box The WordWrap property defines whether lines wrap on word boundaries

23 Figure 5-4: The Effect of the WordWrap Property

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

25 Determining the Length of a String ( Length ) The 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()

26 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

27 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

28 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

29 The IndexOf Method (Syntax, continued) The IndexOf method searches for a substring within a string –The method returns the character position of the first character in the string where the substring was found –The method returns -1 if the substring was not found The first argument named value contains the substring The optional second argument contains the starting position in the string where the search begins The optional third argument contains the number of characters to search

30 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

31 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 The startIndex argument contains the character position where searching will begin The length argument contains the number of characters to search

32 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

33 Figure 5-5: Operation of the Substring Method

34 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 The startIndex argument contains the character position in the existing string where the new string will be inserted –The value is 0-based value contains the string to be inserted

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

36 Figure 5-6: Operation of the Insert Method

37 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 The first method removes all characters from startIndex to the end of the string The second method removes count characters starting at startIndex

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

39 Figure 5-7: Operation of the Remove Method

40 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

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

42 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

43 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"

44 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

45 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

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

47 The System.DateTime Data Type The DataTime data type is a structure, so it is a value type It has members to 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

48 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 = #3/22/2006#

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

50 Members of the DateTime Structure The Now method gets the current date and time The 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

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

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

53 Converting Dates to Strings The ToString method converts a date to a string 8/27/2006 10:49:48 AM The ToLongDateString method converts a date to a string using the system's long date format Sunday, August 27, 2006 The ToShortDateString method converts a date to a string using the system's short date format 8/27/2006

54 Converting Dates to Strings (continued) The ToLongTimeString method converts a date to a string using the system's long time format 10:49:48 AM The ToShortTimeString method converts a date to a string using the system's short time format 10:49 AM

55 Performing Calculations on Dates AddHours, AddMintutes, AddSeconds add time intervals to a date AddYears, AddMonths, AddDays add date intervals to a day DaysInMonth returns the number of days in a particular month

56 Performing Calculations on Dates (Example) Call the date arithmetic methods Dim NextDay As DateTime = Today.AddDays(1) Dim NextMonth As DateTime = Today.AddMonths(1) Dim NextYear As DateTime = Today.AddYears(1) Dim LastDay As DateTime = Today.AddDays(–1) Dim LastMonth As DateTime = _ Today.AddMonths(–1) Dim LastYear As DateTime = Today.AddYears(– 1)

57 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 number of fractional days are stored in the TotalDays, TotalMinutes, and TotalSeconds properties

58 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

59 The DateDiff Method (Syntax) The DateDiff method performs arithmetic on dates –The method returns a Long containing the number of elapsed date or time intervals result = DateDiff(interval, date1, date2 [, firstDayOfWeek [, firstWeekOfYear]])

60 The DateDiff Method (Syntax, continued) The interval argument has a data type of DateInterval –The enumeration contains the list of valid intervals The date1 and date2 arguments contain the input dates –If date1 is greater than date2, the result is negative The firstDayOfWeek and firstWeekOfYear arguments define the day considered the first day of the week and the week considered the first week of the year

61 The DateDiff Method (Example) Dim StartDate, EndDate As DateTime Dim Elapsed As Long StartDate = System.DateTime.Today EndDate = System.DateTime.Today.AddMonths(22) Elapsed = DateDiff(DateInterval.Month, StartDate, _ EndDate, FirstDayOfWeek.Monday, FirstWeekOfYear.Jan1) Elapsed = DateDiff(DateInterval.Year, StartDate, _ EndDate, FirstDayOfWeek.Monday, FirstWeekOfYear.Jan1)

62 The DateTimePicker Control The DateTimePicker control gives the end user an easy way to select a date using a visual calendar –Arrows let the 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

63 Figure 5-11: DateTimePicker Control Instance with Calendar Exposed

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

65 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

66 The Timer Control (Example)


Download ppt "Chapter 5 The String and DateTime Data Types. Class 5: String & DateTime Understand the use of characters and strings Call members of the String class."

Similar presentations


Ads by Google