1 / 107

Chapter 16 Strings, Characters and Regular Expressions (218)*

Chapter 16 Strings, Characters and Regular Expressions (218)*. String Are Important. C# .Net Support for strings is built-in . Brief Intro. using System; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace AllStrings {

daxia
Télécharger la présentation

Chapter 16 Strings, Characters and Regular Expressions (218)*

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 16Strings, Characters and Regular Expressions (218)*

  2. String Are Important • C# • .Net Support for strings is built-in

  3. Brief Intro using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceAllStrings { classAllStrings { publicstaticvoid Main(string[] args) { stringaString = " This is a path c:\MIS"; Console.WriteLine(aString); Console.ReadLine(); } } } error C:\\MIS

  4. Escape sequence \' - single quote, needed for character literals \" - double quote, needed for string literals \\ - backslash \0 – Null \a - Alert \b - Backspace \f - Form feed(It skips to the start of the next page. (Applies mostly to terminals where the output device is a printer.) \n - New line \r - Carriage return \t - Horizontal tab \v - Vertical quote \u - Unicode escape sequence for character \U - Unicode escape sequence for surrogate pairs. \x - Unicode escape sequence similar to "\u" except with variable length.

  5. String and string string is an alias for System.String. Technically, there is no difference. Similar intamdSystem.int32 string place = "world"; String if you need to refer specifically to the class: string greet = String.Format("Hello {0}!", place);

  6. string.Format publicstaticvoid Main(string[] args) { //string aString = " This is a path c:\\MIS"; //string aString = string.Format("{0}", "Hello"); //string aString = string.Format("{0} this {1}", "Hello", "World"); //string aString = string.Format("Coke is {0:C}", 1.99); //run-time currency //string aString = string.Format("Comma and decimals {0:N}", 123456789); stringaString = string.Format("Percent {0:P}", 0.123); Console.WriteLine(aString); Console.ReadLine(); }

  7. String Format custom publicstaticvoid Main(string[] args) { string phone = string.Format("My phone {0:(###) ###- ####}", 1234567890); phone); Console.ReadLine(); } http://msdn.microsoft.com/en-us/library/system.string.format.aspx

  8. String concatenation publicstaticvoid Main(string[] args) { string s = ""; for(int i = 0; i < 50; i++) { //s = s + " + " + i.ToString(); s += " + " + i; //creates 50 new strings! } Console.WriteLine(s); }

  9. StringBuilder StringBuildersb = newStringBuilder(); for(int i = 0; i < 100; i++) { //sb.Append(" + "); //sb.Append(i); sb.Append(" + ").Append(i); } Console.WriteLine(sb.ToString()); //same Console.WriteLine(sb); Console.ReadLine();

  10. Crunching strings • Substring StringaString = "No class next time, but there is an assignment"; aString= aString.Substring(0, 18); Console.WriteLine(aString); Console.ReadLine(); ToUpper, ToLower aString= aString.ToUpper(); • Replace aString= aString.Replace(" ", "_"); • Trim • Length (before and after trimming) aString.Trim().Length() //chaining Capital Does not matter

  11. 16.2 Fundamentals of Characters and Strings Characters are the fundamental building blocks of C# source code. Every program is composed of characters that, when grouped together meaningfully, create a sequence that the compiler interprets as instructions describing how to accomplish a task. A program also can contain character constants.

  12. 16.2 Fundamentals of Characters and Strings • A character constant is a character that’s represented as an integer value, called a character code. • For example, the integer value 122 corresponds to the character constant 'z'. • The integer value 10 corresponds to the newline character '\n'. • Character constants are established according to the Unicode character set, an international character set that contains many more symbols and letters than does the ASCII character set

  13. 16.2 Fundamentals of Characters and Strings (cont.) A string is a series of characters treated as a unit. These characters can be uppercase letters, lowercase letters, digits and various special characters: +, -, *, /, $ and others. A string is an object of class stringin the System namespace. In C#, the string keyword is an alias for String. Therefore, String and string are equivalent, and you can use whichever naming convention you prefer.

  14. 16.2 Fundamentals of Characters and Strings (cont.) • string literals, also called string constants, as sequences of characters in double quotation marks, as follows: "John Q. Doe" "9999 Main Street" "Waltham, Massachusetts" "(201) 555-1212"

  15. 16.2 Fundamentals of Characters and Strings (cont.) • A declaration can assign a string literal to a string reference. The declaration string color = "blue"; • initializes the string color to refer to the string literal object "blue".

  16. 16.2 Fundamentals of Characters and Strings

  17. 16.2 Fundamentals of Characters and Strings (cont.) Verbatim Strings On occasion, a string will contain multiple backslash characters (this often occurs in the name of a file). To avoid excessive backslash characters, it’s possible to exclude escape sequences and interpret all the characters in a string literally, using the @ character to create what’s known as a verbatim string. Backslashes within the double quotation marks following the @ character are not considered escape sequences.

  18. 16.2 Fundamentals of Characters and Strings (cont.) • For example, consider the string "C:\MyFolder\MySubFolder\MyFile.txt" with the following assignment: stringfile = "C:\\MyFolder\\MySubFolder\\MyFile.txt"; • Using the verbatim string syntax, the assignment can be altered to stringfile = @"C:\MyFolder\MySubFolder\MyFile.txt";

  19. 16.3 string Constructors Class stringprovides eight constructors for initializing strings in various ways. Figure 16.1 demonstrates three of the constructors.

  20. 16.3 string Constructors Class string provides eight constructors for initializing strings in various ways. Figure 16.1 demonstrates three of the constructors.

  21. 16.3 string Constructors

  22. 16.4 string Indexer, Length Property and CopyTo Method The app in Fig. 16.2 presents the stringindexer, which facilitates the retrieval of any character in the string, and the string property Length, which returns the length of the string. The string method CopyTo copies a specified number of characters from a string into a char array.

  23. 16.4 string Indexer, Length Property and CopyToMethod String indexer

  24. important

  25. 16.5 Comparing strings Comparing Strings with Equals, CompareTo and the Equality Operator (==) Class string provides several ways to compare strings. The app in Fig. 16.3 demonstrates the use of method Equals, method CompareTo and the equality operator (==).

  26. 16.5 Comparing strings Content comparison

  27. Overloaded operator content comparison

  28. object.ReferenceEquals()

  29. 16.5 Comparing strings (cont.) Determining Whether a String Begins or Ends with a Specified String Figure 16.4 shows how to test whether a string instance begins or ends with a given string.

  30. 16.6 Locating Characters and Substrings in strings In many apps, it’s necessary to search for a character or set of characters in a string. For example, a programmer creating a word processor would want to provide capabilities for searching through documents. The app in Fig. 16.5 demonstrates some of the many versions of string methods IndexOf, IndexOfAny, LastIndexOf and LastIndexOfAny, which search for a specified character or substring in a string. All searches in this example on the string letters (initialized with "abcdefghijklmabcdefghijklm") located in method Main of class StringIndexMethods.

  31. 16.6 Locating Characters and Substrings in strings

  32. 16.7 Extracting Substrings from strings Class stringprovides two Substring methods, which create a new string by copying part of an existing string. Each method returns a new string. The app in Fig. 16.6 demonstrates the use of both methods.

  33. 16.7 Extracting Substrings from strings

  34. 16.8 Concatenating strings The + operator is not the only way to perform string concatenation. The static method Concat of class string (Fig. 16.7) concatenates two strings and returns a new string containing the combined characters from both original strings.

  35. 16.8 Concatenating strings

  36. 16.9 Miscellaneous string Methods Class stringprovides several methods that return modified copies of strings. The app in Fig. 16.8 demonstrates the use of these methods, which include string methods Replace, ToLower, ToUpper and Trim.

  37. 16.9 Miscellaneous string Methods

  38. 16.11 Class StringBuilder string’s contents can never change. Operations that seem to concatenate strings are in fact creating new strings—the += operator creates a new string and assigns its reference to the variable on the left of the += operator. Every StringBuilder can store a certain number of characters that’s specified by its capacity. Exceeding the capacity of a StringBuilder causes the capacity to expand to accommodate the additional characters.

  39. 16.11 Class StringBuilder(cont.) Members of class StringBuilder , such as methods Append and AppendFormat, can be used for concatenation like the operators + and += for class string. StringBuilder is particularly useful for manipulating in place a large number of strings, as it’s much more efficient than creating individual immutable strings.

More Related