software development
play

SOFTWARE DEVELOPMENT 7th LECTURE Reminder Deadline next week - PowerPoint PPT Presentation

SOFTWARE DEVELOPMENT 7th LECTURE Reminder Deadline next week (week 8) So far things are... Today Working with Strings Formatting values Data validation Working with data collections Reflection Dynamic


  1. SOFTWARE DEVELOPMENT 7th LECTURE

  2. Reminder • Deadline – next week (week 8) • So far things are...

  3. Today • Working with Strings • Formatting values • Data validation • Working with data collections • Reflection • Dynamic • Attributes

  4. String • String – immutable reference type – When using Replace or ToUpper a reference to newly created string is returned. • Intern pool : – For optimal work, CLR saves references to unique string type values in intern pool . – Different String type variables with same values points to same adress in the intern pool. • Common ways of creation: – By assigning specific value – Reading from element (like TextBox or ComboBox) – By assigning operation result.

  5. Immutable types • Makes it easy for concurent programming: – Main problem – how threads are accessing resources? – E.g. – race conditions . • string – immutable type:

  6. Comparing strings • What will be printed out? • True

  7. Working with String • What will be printed out? • False • True

  8. Working with String • Main constructors: – By giving char array – By giving char array with starting and ending indexes – By giving char and repetition count: • Properties: – Empty – Length – Read-only indexer • To change specific chars , one needs to convert to char array or use Replace method(s)

  9. String.Empty vs „“ vs null • String.empty: – read-only constant. – Used when creating String variable, when it's not clear, when value will appear. – Not possible to use with Case and Deault: • „“ – Constant created on compile time – "" == string.Empty • null – no reference at all.

  10. String methods Method Description Compares two Strings and returns – 1, 0, or 1 to indicate that the first String should be Compare considered before, equal to, or after the second String in the sort order. Takes as a parameter an array of Strings or other objects and returns a String holding the Concat concatenation of the objects. Copy Returns a copy of the String. Equals Returns true if two Strings have the same value. Format PUses a format string and a series of objects to generate a formatted text string. IsNullOrEmpty Returns true if the String holds a blank string "" or the String variable refers to null. All true : string value1 = ""; string value2 = String.Empty; string value3 = null; Returns true if the String variable holds a blank string, refers to null, or IsNullOrWhiteS holds only whitespace characters. Whitespace characters are those for which pace Char.IsWhiteSpace returns true. Join Joins the values in an array of strings or other objects separated by a separator string. string[] weekdays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; string allDays = string.Join(",", weekdays);

  11. String instance methods • Comparing: – CompareTo (in order) and Equals (for equality) • Substring search: – Contains, EndsWith, StartsWith • Index finding: – IndexOf, IndexOfAny, LastIndexOf, LastIndexOfAny • Changing the value: – ToUpper, ToLower, Insert, Remove, Replace – Space changing and etc.: Trim, TrimEnd, TrimStart, PadLeft, PadRight • Convert to array: – CopyTo, ToCharArray, Split

  12. String : special symbols • \' • \" • \\ • \0 - Unicode 0 • \n - new line (character 10) • \r - return (character 13)

  13. Fun facts • Space in memory: – 20+(n/2)*4 – Saved in memory: • Array of char size • String size • Char values • Similar to... arrays :)

  14. StringBuilder • Working with String is slow, since it's immutable • Self-study: – How slow - string.cs • How to avoid:

  15. StringBuilder: props and methods Description Property Gets or sets the number of characters that can be held by the StringBuilder. If Capacity the amount of text stored in the StringBuilder exceeds this amount, the object allocates more space. If you know the StringBuilder needs to hold at least a certain number of characters, you can use this property to make the object pre- allocate memory instead of allocating memory incrementally.. Gets or sets the current number of the characters stored. Cuts if lower. Length Method Description Appends a string representation of an object to the end Append Formats a series of objects and appends the result to the end AppendFormat Ensures that the StringBuilder has at least a given capacity EnsureCapacity Inserts a string representation of an object at a given position Insert Removes a range of characters from the StringBuilder’s text Remove Replaces all instances of a character or string with a new Replace Returns a normal String representation of the StringBuilder’s text ToString

  16. Formating data • ToString – Class Object has ToString() method, all other classes inherts it. – Standard method behavior – print out object type, • Most of the time it is overloaded – For double value of 5.25 ToString() returns „ 5.25 “ . – For double value of 5.25 ToString() returns „ 05.250 “ . – What will be printed out? – Answer in ToString.cs – Extra info: Custom Numeric Format Strings (MSDN)

  17. Formating data • Repetition: • For numeric types (FormatString): Example Directive Description C or c Currency $12,345.67 D or d Decimal (integer types only) 12345 E or e Scientific notation 1.234567E+004 F or f Fixed-point 12345.67 G or g Default General (fixed-point or scientific, whichever is 12345.67 shorter) N or n Number (with decimal and thousands separators) 12,345.67 P or p Percent (multiplied by 100 and % added) 0.12 becomes 12.00 % X or x Hexadecimal (integer types only) 3039

  18. Formating data • String.Format – For each object to be formated this syntax applies: {index[,length][:formatString]} – {0} first argument, with standard formatting – {1,4} second argument, which will take at least four spaces – {2:X} third argument with HEX format – What will be printed if i == 97?

  19. Formating data string name = "Mark"; var date = DateTime.Now; // Composite formatting: Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date); // String interpolation: Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now."); // Both calls produce the same output that is similar to: // Hello, Mark! Today is Wednesday, it's 19:40 now.

  20. Formating data • Date and time: Letter Description Example d Short date 3/14/2014 D Long date Friday, March 14, 2012 f “Full” with short time Friday, March 14, 2012 2:15 PM F “Full” with long time Friday, March 14, 2012 2:15:16 PM g “General” with short time 3/14/2014 2:15 PM G “General” with long time 3/14/2014 2:15:16 PM m or M Month/day March 14 t Short time 2:15 PM T Long time 2:15:16 PM y or Y Year/month March, 2014 • Other methods: – ToShortDateString, ToLongDateString, ToShortTimeString, ToLongTimeString.

  21. Data validation • Data validation – checking, if inputed data is correct. • Ideally, we would catch it as soon as possible. • Best way – avoid it at all, for example: – numericUpDown – DateTimePicker – Etc. • It helps avoid not only checking, but spaming the user as well.

  22. Regex • Regular expression (regex) allows: – Determine, if given string matches the pattern, which is called regular expression. – Find parts of the string matching the pattern. – Change parts of the string matching the pattern. • Main class: – System.Text.RegularExpressions.Regex • More - in the course of internet technologies .

  23. Regex methods Method Description Returns true if a regular expression matches a string. IsMatch Match Searches a string for the first part of it that matches a regular expression. Returns a collection giving information about all parts of a string that match Matches a regular expression. Replace Replaces some or all the parts of the string that match a pattern with a new value. This is more powerful than the string class’s Replace method. Split Splits a string into an array of substrings delimited by pieces of the string that match a regular expression

  24. Regex exmples • Does string have more than one digit? Return those digits:

  25. Regex • For pattern we need to escape - “ \ ” : – C# reads „ \ “ as a special char – So to print "\n" you need to escape the "\" • Console.WriteLine („ testas\\ntestas") • Console.WriteLine(@" testas\ntestas"); – Most common ones are: \n ir \t

  26. Regex: anchors • Anchors define, where pattern should be matched • Multiline is to be considered • Main ones: Anchor Description String start, or new line in multiline. ^ String end, or end of line in multiline. $ Line start \A Line end \Z

  27. Regex: simple example • pattern = @"^\d{3}-\d{4}$"; Part Description Defines start of the string. ^ \d Any digit {3} Repeats last part 3 times – Matches symbol „ - “ \d Any digit Repeats last part 4 times {4}

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend