Category Archives: C# Programming

Chapter19:DateTimeMethods

Section19.1:DateTimeFormatting StandardDateTimeFormatting DateTimeFormatInfo specifies a set of specifiers for simple date and time formatting. Every specifier correspond to a particular DateTimeFormatInfo format pattern.…
Continue reading

Chapter18:RegexParsing

Section18.1:Singlematch usingSystem.Text.RegularExpressions; stringpattern=":(.*?):"; stringlookup="--:textinhere:--"; //Instanciateyourregexobjectandpassapatterntoit RegexrgxLookup=newRegex(pattern,RegexOptions.Singleline,TimeSpan.FromSeconds(1)); //Getthematchfromyourregex-object MatchmLookup=rgxLookup.Match(lookup); //Thegroup-index0alwayscoversthefullpattern. //Matchesinsideparentheseswillbeaccessedthroughtheindex1andabove. stringfound=mLookup.Groups[1].Value; Result: found="textinhere" Section18.2:Multiplematches usingSystem.Text.RegularExpressions; List<string>found=newList<string>(); stringpattern=":(.*?):"; stringlookup="--:textinhere:--:anotherone:-:thirdone:---!123:fourth:"; //Instanciateyourregexobjectandpassapatterntoit RegexrgxLookup=newRegex(pattern,RegexOptions.Singleline,TimeSpan.FromSeconds(1)); MatchCollectionmLookup=rgxLookup.Matches(lookup); foreach(MatchmatchinmLookup) {…
Continue reading

Chapter17:StringBuilder

Section17.1:WhataStringBuilderisandwhentouseone AStringBuilderrepresentsaseriesofcharacters,whichunlikeanormalstring,aremutable.Oftentimesthereisa needtomodifystringsthatwe'vealreadymade,butthestandardstringobjectisnotmutable.Thismeansthateach timeastringismodified,anewstringobjectneedstobecreated,copiedto,andthenreassigned. stringmyString="Apples"; mystring+="aremyfavoritefruit"; Intheaboveexample,myStringinitiallyonlyhasthevalue"Apples".However,whenweconcatenate`"aremy favoritefruit"',whatthestringclassdoesinternallyneedstodoinvolves: CreatinganewarrayofcharactersequaltothelengthofmyStringandthenewstringweareappending. CopyingallofthecharactersofmyStringintothebeginningofournewarrayandcopyingthenewstringinto the end of the array. CreateanewstringobjectinmemoryandreassignittomyString. For a single concatenation, this is relatively…
Continue reading

Chapter16:StringEscapeSequences

Section16.1:Escapingspecialsymbolsinstringliterals Backslash //Thefilenamewillbec:\myfile.txtinbothcases stringfilename="c:\\myfile.txt"; stringfilename=@"c:\myfile.txt"; Thesecondexampleusesaverbatimstringliteral,whichdoesn'ttreatthebackslashasanescapecharacter. Quotes stringtext="\"HelloWorld!\",saidthequickbrownfox."; stringverbatimText=@"""HelloWorld!"",saidthequickbrownfox."; Bothvariableswillcontainthesame text. "Hello World!", said the quickbrown fox. Newlines Verbatim string literals can contain…
Continue reading

Chapter15:StringInterpolation

Section15.1:Formatdatesinstrings vardate=newDateTime(2015,11,11); varstr=$"It's{date:MMMMd,yyyy},makeawish!"; System.Console.WriteLine(str); YoucanalsousetheDateTime.ToStringmethodtoformattheDateTimeobject.Thiswillproducethesameoutput as the code above. vardate=newDateTime(2015,11,11); varstr=date.ToString("MMMMd,yyyy"); str="It's"+str+",makeawish!"; Console.WriteLine(str); Output: It'sNovember11,2015,makeawish! LiveDemoon.NETFiddle LiveDemousingDateTime.ToString Note:MMstandsformonthsandmmforminutes.Beverycarefulwhenusingtheseasmistakescan introduce bugs that may be…
Continue reading

Chapter14:StringManipulation

Section14.1:Replacingastringwithinastring UsingtheSystem.String.Replacemethod,youcanreplacepartofastringwithanotherstring. strings="HelloWorld"; s=s.Replace("World","Universe");//s="HelloUniverse" Alltheoccurrencesofthesearchstringarereplaced: strings="HelloWorld"; s=s.Replace("l","L");//s="HeLLoWorLD" String.Replacecanalsobeusedtoremovepartofastring,byspecifyinganemptystringasthereplacementvalue: strings="HelloWorld"; s=s.Replace("ell",String.Empty);//s="HoWorld" Section14.2:Findingastringwithinastring UsingtheSystem.String.Containsyoucanfindoutifaparticularstringexistswithinastring.Themethodreturns aboolean,trueifthestringexistselsefalse. strings="HelloWorld"; boolstringExists=s.Contains("ello");                         //stringExists=trueasthestringcontainsthesubstring UsingtheSystem.String.IndexOfmethod,youcanlocatethestartingpositionofasubstringwithinanexisting string. Notethereturnedpositioniszero-based,avalueof-1isreturnedifthesubstringisnotfound. strings="HelloWorld"; intlocation=s.IndexOf("ello");//location=1 Tofindthefirstlocationfromtheendofastring,usetheSystem.String.LastIndexOfmethod: strings="HelloWorld";…
Continue reading

Chapter13:StringConcatenate

Section13.1:+Operator strings1="string1"; strings2="string2"; strings3=s1+s2;//"string1string2" Section 13.2: Concatenate strings using System.Text.StringBuilder Concatenating strings using a StringBuildercan offer performance advantages over simple string concatenation using+.Thisisduetothewaymemoryisallocated.Stringsarereallocatedwitheachconcatenation,StringBuilders…
Continue reading

Chapter12:String.Format

TheFormatmethodsareasetofoverloadsintheSystem.Stringclassusedtocreatestringsthatcombineobjects intospecificstringrepresentations.ThisinformationcanbeappliedtoString.Format,variousWriteLinemethods aswellasothermethodsinthe.NETframework. Section12.1:SinceC#6.0 Version ≥ 6.0 SinceC#6.0itispossibletousestringinterpolationinplaceofString.Format. stringname="John"; stringlastname="Doe"; Console.WriteLine($"Hello{name}{lastname}!"); Hello JohnDoe! MoreexamplesforthisunderthetopicC#6.0features:Stringinterpolation. Section12.2:PlaceswhereString.Formatis'embedded'inthe framework ThereareseveralplaceswhereyoucanuseString.Formatindirectly:Thesecretistolookfortheoverloadwiththe signaturestringformat,paramsobject[]args,e.g.: Console.WriteLine(String.Format("{0}-{1}",name,value)); Canbe replacedwith shorterversion: Console.WriteLine("{0}-{1}",name,value);…
Continue reading

Chapter11:CommonStringOperations

Section11.1:Formattingastring UsetheString.Format()methodtoreplaceoneormoreitemsinthestringwiththestringrepresentationofa specified object: String.Format("Hello{0}Foo{1}","World","Bar")//HelloWorldFooBar Section11.2:Correctlyreversingastring Mosttimeswhenpeoplehavetoreverseastring,theydoitmoreorlesslikethis: char[]a=s.ToCharArray(); System.Array.Reverse(a); stringr=newstring(a); However, what these people don't realize is that this is actually wrong. And…
Continue reading

Chapter10:VerbatimStrings

Section10.1:InterpolatedVerbatimStrings VerbatimstringscanbecombinedwiththenewStringinterpolationfeaturesfoundinC#6. Console.WriteLine($@"Testing\n12{5-2} Newline"); Output: Testing\n123 New line LiveDemoon.NETFiddle Asexpectedfromaverbatimstring,thebackslashesareignoredasescapecharacters.Andasexpectedfroman interpolated string, any expression inside curly braces is evaluated before being inserted into…
Continue reading