4)string and date time manipulation

Upload: sangeetha-sangu-bc

Post on 06-Jul-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/17/2019 4)String and Date Time Manipulation

    1/7

    String:

     A string is traditionally a sequence of characters, either as a literal constant or as some kind of

    variable.

    Strings are mutable and immutable; let us have a description on it.

    Mutable Strings:

    Mutable strings are those strings which can be modified. In general way when we modifyan existing string in C# we think that we have applied the changes to the existingobect! in fact when we done any kind of modification in string a new obect is created

    which refer to that modified string and the old one become unreferenced and as a resultthe garbage collector then collect that unreferenced obect. If there is situation occurs

    that we are continuously modifying the string then the no. of unreferenced obect willincrease then it will be the overhead for the garbage collector to free the unreferenced

    obect. "hus! in this case rather than using string class we will use Stringuilder class."his class allows the modification in the same obect. "hus in this case the overhead ofthe garbage collector will be reduced and the performance of the program will beincrease.

    Lets have a look on the following operation which are associated with theStringBuilder class.

     

    Property or Method Description

    $ength %ets the no. of character that the Stringuilder obect contains.

    Capacity %ets the current capacity of the Stringuilder obect.

    &ppend'( &ppend the string representation of the specified obect at the end of thisStringuilder instance.

    Insert'(&ppend the string representation of the specified obect at the specifiedindex of this Stringuilder instance.

    )eplace'string!string()eplaces all the occurrence of the first supplied string with the second

    supplied string in this Stringbuilder obect.

    )emove'int st!int length()emove all characters from the index position st of specified length in the

    current Stringuilder obect.

    *+uals'Stringuilder(Checks the supplied stringbuilder obect with this instance , returns true ifboth are identical-otherwise!it returns false.

    using System."ext; 

    namespace Console&pplication/

      class 0rogram  /

      static void Main'string12 args(  /  Stringuilder sb 3 new Stringuilder'4"his book4(;  string s 3 4is completed4;  Console.5rite$ine'4$ength of the stringbuilder /67 is/874!sb!sb.$ength(;

      Console.5rite$ine'4Capacity of the stringbuilder /67is /874!sb!sb.Capacity(;

    http://en.wikipedia.org/wiki/Character_(computing)http://en.wikipedia.org/wiki/Character_(computing)http://en.wikipedia.org/wiki/Literal_(computer_programming)http://en.wikipedia.org/wiki/Literal_(computer_programming)http://en.wikipedia.org/wiki/Literal_(computer_programming)http://en.wikipedia.org/wiki/Character_(computing)

  • 8/17/2019 4)String and Date Time Manipulation

    2/7

      Console.5rite$ine'4Stringuilder before appending is/674! sb(;

      Console.5rite$ine'4Stringuilder after appending /67is /874!s!sb.&ppend's((;

      Console.5rite$ine'4stringbuilder after inserting now is/674!sb.Insert'88!4now4((;  Console.5rite$ine'4Stringuilder after removing 9is9 is/674!sb.)emove'!:((;  Console.5rite$ine'4Stringbuilder replacing all 9o9 with9x9 is /674! sb.)eplace'9o9! 9x9((;

      Console.)ead$ine'(;  7

      77

    Immutable Strings

    n C# 'and .*"( a string is represented by class System.String. "he 9string9 keyword is

    an alias for this class.

    "he System.String class is immutable i.e once created its state cannot be

    altered.

    So all the operations you perform on a string like Substring! )emove! )eplace!

    concatenation using 9

  • 8/17/2019 4)String and Date Time Manipulation

    3/7

    DateTime em5tyDateTime " new DateTime#)*  6ust dateDateTime justDate " new DateTime#(''(, 1', 17)*  DateTime from Ticks

    DateTime justTime " new DateTime#1'''''')*  DateTime with localizationDateTime dateTime3ith8ind " new DateTime#1$%&, %, 1', %, 1', (&, DateTime8ind.Local)*  DateTime with date, time and millisecondsDateTime dateTime3ithilliseconds " new DateTime#('1', 1(, 19, 9, :', &9, 1'')*

    Date"ime Properties- 

     The Date and the Time 5ro5erties of DateTime get the date and the timeof a DateTime. +ome self;eear, onth, and Day. =ere is a list of some other 5ro5erties with their brief descri5tion.

    • Day?f3eek 5ro5erty returns the name of the day in a week.

    • Day?f>ear 5ro5erty returns the day of a year.

    •  Time?fDay 5ro5erty returns the time element in a DateTime.

    •  Today 5ro5erty returns the DateTime object that has today@s values. Time value is 1(-''-''.

    • ow 5ro5erty returns a DateTime object that has right now date andtime values.

    • Btcow 5ro5erty returns a DateTime in !oordinated Bniversal Time#BT!)

    • A tick re5resents one hundred nanoseconds or one ten;millionth of a

    second. Ticks 5ro5erty of DateTime returns the number of ticks in aDateTime.

    • 8ind 5ro5erty returns a value that indicates whether the timere5resented by this instance is based on local time, !oordinatedBniversal Time #BT!), or neither. The default value is uns5eciCed.

     The code listed in Listing ( creates a DateTime object and readsits 5ro5erties. DateTime dob " new DateTime#1$%&, %, 1', %, 1', (&)*

  • 8/17/2019 4)String and Date Time Manipulation

    4/7

    !onsole.3riteLine#Day-'E, dob.Day)*!onsole.3riteLine#onth-'E, dob.onth)*!onsole.3riteLine#>ear-'E, dob.>ear)*!onsole.3riteLine#=our-'E, dob.=our)*!onsole.3riteLine#inute-'E, dob.inute)*!onsole.3riteLine#+econd-'E, dob.+econd)*

    !onsole.3riteLine#illisecond-'E, dob.illisecond)* !onsole.3riteLine#Day of 3eek-'E, dob.Day?f3eek)*!onsole.3riteLine#Day of >ear- 'E, dob.Day?f>ear)*!onsole.3riteLine#Time of Day-'E, dob.Time?fDay)*!onsole.3riteLine#Tick-'E, dob.Ticks)*!onsole.3riteLine#8ind-'E, dob.8ind)*

     Listing 2

     

     The out5ut of Listing ( looks like /igure 1. 

    Figure 1 

    #dding and Subtracting Date"ime- 

    DateTime structure 5rovides methods to add and subtract date and timeto and from a DateTime object. The Time+5an structure 5lays a major rolein addition and subtraction. 

    3e can use Add and +ubtract methods to add and subtract date and timefrom a DateTime object. /irst we create a Time+5an with a date andortime values and use Add and +ubtract methods.  The code listed in Listing : adds and subtracts :' days from today anddis5lays the day on the console. DateTime aDay " DateTime.ow*

     Time+5an aonth " new +ystem. Time+5an#:', ', ', ')*DateTime aDayAfterAonth " aDay.Add#aonth)*DateTime aDayFeforeAonth " aDay.+ubtract#aonth)*

    !onsole.3riteLine#'-ddddE, aDayAfterAonth)*!onsole.3riteLine#'-ddddE, aDayFeforeAonth)* 

  • 8/17/2019 4)String and Date Time Manipulation

    5/7

    Listing 3 

     The DateTime structure has methods to add years, days, hours, minutes,seconds, milliseconds and ticks. The code listed in Listing & uses theseAddears#()*aDay.AddDays#1()* Add =ours, inutes, +econds, illiseconds, and TicksaDay.Add=ours#&.(9)*aDay.Addinutes#19)*aDay.Add+econds#&9)*aDay.Addilliseconds#('')*aDay.AddTicks#9''')*

    Listing 4 

     The DateTime structure does not have similar +ubtract methods. ?nly+ubtract method is used to subtract the DateTime com5onents. /oreear, dob.onth, dob.Day, dob.=our ; 1, dob.inute ; 19,dob.+econd ; 19)*!onsole.3riteLine#hms.To+tring#))*

    Listing 5 $ind Days in a Month 

     The Days2nonth static method returns the number of days in a month. This method takes a year and a month in numbers from 1 to 1(. The code

  • 8/17/2019 4)String and Date Time Manipulation

    6/7

    sni55et in Listing G gets the number of days in /eb month of year (''(. The out5ut is (7 days. int days " DateTime.Days2nonth#(''(, ()*!onsole.3riteLine#days)*

    Listing 6 Bsing the same a55roach, we can Cnd out total number of days in a year. The etDays2nA>ear method in Listing % takes a year and returns totalnumber of days in that year. 5rivate int etDays2nA>ear#int year)  int days " '*  for #int i " 1* i I" 1(* iJJ)    days J" DateTime.Days2nonth#year, i)*  E

      return days*E 

    Listing 7!ompare "wo Date"ime 

     The !om5are static method is used to com5are two DateTime objects. 2fresult is ', both objects are the same. 2f the result is less than ', then theCrst DateTime is earlier* otherwise the Crst DateTime is later.  The code sni55et in Listing 7 com5ares two DateTime objects. DateTime CrstDate " new DateTime#(''(, 1', (()*DateTime secondDate " new DateTime#(''$, 7, 11)*int result " DateTime.!om5are#CrstDate, secondDate)* if  #result I ')  !onsole.3riteLine#/irst date is earlier)*else if  #result "" ')  !onsole.3riteLine#Foth dates are same)*else  !onsole.3riteLine#/irst date is later)* 

    Listing 8

      The !om5areTo method can also be used to com5are two dates. Thismethod takes a DateTime or object. The code sni55et in Listing $com5ares two DateTime objects using the !om5areTo method. DateTime CrstDate " new DateTime#(''(, 1', (()*DateTime secondDate " new DateTime#(''$, 7, 11)*int com5areKesult " CrstDate.!om5areTo#secondDate)*if  #com5areKesult I ')  !onsole.3riteLine#/irst date is earlier)*else if  #com5areKesult "" ')  !onsole.3riteLine#Foth dates are same)*else

      !onsole.3riteLine#/irst date is later)*

     

  • 8/17/2019 4)String and Date Time Manipulation

    7/7

    Listing 9$ormatting Date"ime- 

    2 have to admit* the folks at icrosoft have done a great job of 5rovidingDateTime formatting solutions. ow you can format a DateTime to any

    kind of string format you can imagine.  The etDateTime/ormats method returns all 5ossible DateTime formatsfor the current culture of a com5uter. The code sni55et in Listing 1'returns an array of strings of all 5ossible standard formats. DateTime dob " new DateTime#(''(, 1', (()*stringM date/ormats " dob.etDateTime/ormats#)*foreach #string format in date/ormats)  !onsole.3riteLine#format)

    Listing 10 

     The code sni55et in Listing 1' generates out5ut as in /igure (.