Chapter 8 ISM 3232

8.1 Introduction

...

Introduction

• Have used strings so far for input and output, including reading from keyboard and files and writing to the screen and to files.• Can also perform operations on strings as used by- Word processing programs- Email programs- Search engines and more• C# and .NET Framework have tools and techniques used to examine and manipulate strings.

8.2 Working with Characters

...

Working with Characters

The char data type is used to store individual characters.• Character literals are enclosed in single quotations marks.- Don't confuse with string literals which, even including only a single character, are enclosed in double quotation marks.

The char Data Type

• A char variable can hold only one character at a time- This statement declares a char variable named letter:char letter;• Character literals are enclosed in single quotation marks ( ' )- This statement assigns the character g to the letter variable:letter = 'g';• char and string are two incompatible data types- This attempt to assign a string to a char variable will not compile:letter = "g"; // Causes a compiler error- Use the ToString method to convert a char value to a string value:MessageBox.Show(letter.ToString());

8.2 Working with Characters example

Write a statement to declare a char variable gradeand assign letter A as its value.Answer: char grade = 'A'; √char grade = "A"; ו Assume a char variable grade has been declared. Write a statement to display its value in a message box.Answer: MessageBox.Show(grade.ToString());Part 1min 4:24

Retrieving the Characters in a String

• C# accesses the individual characters in a string using subscript notation• The subscript 0 refers to the first character in the string. In a string of length n, the last character has subscript n - 1- A string can be treated as an array of characters:string name = "Jacob";char letter;for (int index = 0; index < name.Length; index++){letter = name[index]; // Read next character in stringMessageBox.Show(letter.ToString()); // Display it}- Elements in the string array are read-only and their values cannot be changed; for example, the following will not compile:name[0] = 'T'; // Attempt to assign a new value will fail

8.2 Working with Characters example part 2

• Assume a string variable name has been declared. Write a statement to display its 3rd element in a message box. For example, if the value of the string is "Michael", we need to display letter 'c'.Answer: MessageBox.Show(name[2].ToString());• Write a statement to display both its 2nd and 3rd element.• Answer: MessageBox.Show(name[1].ToString() + name[2].ToString());part 1min 10:39

Character Testing Methods

• Mfor testing the value of a character are:- char.IsDigit(ch): checks if ch is a digit (0 through 9)- char.IsDigit(str, index): checks if index of str is a digit- char.IsLetter(ch): checks if ch is alphabetic (a through z or A through Z)- char.IsLetter(str, index): checks if index of str is alphabetic- char.IsLetterOrDigit(ch): checks if ch is a digit or alphabetic- char.IsLetterOrDigit(str, index): checks if index of str is a digit or alphabetic- where ch is a character; str is a string; and index is the position of a character within str// for both IsDigit examples are true

character testing in class example

string str = "z12fw";if (char.IsLetter(str[0]){ MessageBox.Show("True");}string str = "z12fw";if (char.IsLetter(str, 0){ MessageBox.Show("True");}samething string str = "z12fw";if (char.IsLetter(str, 1){ MessageBox.Show("True");}we will not see the messagestring str = "z12fw";if (char.IsLetterOrDigit(str[1]){ MessageBox.Show("True");}It will show the messagestring str = "z12fw";if (char.IsLetterOrDigit(str, 0){ MessageBox.Show("True");}it's true

Character Testing Methods (Cont'd)

• More overloaded methods for testing the value of a char are:- char.IsPunctuation(ch): checks if ch is a punctuation mark- char.IsPunctuation(str, index): checks if index of str is a punctuation mark- char.IsWhiteSpace(ch): checks if ch is a white-space character- char.IsWhiteSpace(str, index): checks if index of str is a white-space character- where ch is a character; str is a string; and index is the position of a character within str

white space example

string str = "z12 fw";if (char.IsWhiteSpace(str, 3){ MessageBox.Show("True");}the message will show"Overloaded version"string str = "z12 fw";if (char.IsWhiteSpace(str[3]){ MessageBox.Show("True");}

Character Testing Methods (Cont'd) 3

• Overloaded methods that check a char letter's case are:- char.IsLower(ch): checks if ch is a lowercase letter- char.IsLower(str, index): checks if index of str is a lowercase letter- char.IsUpper(ch): checks if ch is a uppercase letter- char.IsUpper(str, index): checks if index of str is a uppercase letter- where ch is a character; str is a string; and index is the position of a character within str

Character Testing Methods example

• Assume that a string variable name has been declared. Write a for loop to check if each element in the string is a letter. If the ith element is not a letter, display a message "The ith element is not a letter!"Answer:for (int index = 0; index < name.length; index++){ if(!char.IsLetter(name[index])) { MessageBox.Show("The " + (index+1).ToString() + "th element is not a letter!"); }}part 1min 31:00

Character Case Conversion

Character Case Conversion• The char data type provides two methods to convert between the case of a character:- char.ToLower(ch): returns lowercase equivalent of ch- char.ToUpper(ch): returns uppercase equivalent of ch• For example:string str1 = "ABC";string str2 = "xyz";char letter = char.ToLower(str1[0]); // Converts A into achar letter = char.ToUpper(str2[0]); // Converts x into X

Character Case Conversion example

• Assume that a string variable name has been declared as follows:string name = "ABcDeFg";• Transform all uppercase letters in this string to lowercase letters.• Answer:string name1 = "";for (int index = 0; index<name.length, index++){ if (char.IsUpper(name, index)) { name1 = name1 + char.ToLower(name[index]); } else { name1 = name1 + name[index]; }}part 1min 1:06:39

Character Case Conversion example 2

• Assume that the string variable name1 has been declared as follows:string name1 = "ABcDe";• Transform the uppercase letters in name1 to lowercase letters and lowercase to uppercase letters.part 1min 1:08:04

Declare a char variable named letter and assign the letter'A' to the variable.1

...

Write a statement that displays the value of a char variablenamed letterGrade in a message box.2

...

Write a statement that declares a char variable namedlastLetter and stores the last character of a string namedalphabet in the variable.3

...

Write a foreach loop that displays each character of a stringvariable named serialNumber in a message box.4

...

Write the first line of an if statement that calls thechar. IsPuncuation method and passes the last character of astring variable named sentence as an argument.5

...

8.3 Working with Substrings

...

Working with Substrings

A substring is a string within a string. The .NET Framework provides method for working with and manipulating substrings.

Searching for Substrings

• Some tasks require you to search for a specific string of characters within a string; some of the substring searching methods are:- stringVar.Contains(substring): checks if stringVar contains substring- stringVar.Contains(ch): checks if stringVar contains character ch- stringVar.StartsWith(substring): checks if stringVar starts with substring- stringVar.EndsWith(substring): checks if stringVar ends with substring• where stringVar is the name of a string variable; substring the string to be found; ch is a characterfor the second example it doesn't show the message because it ends with eam! not eam.

Working with Substrings example

Assume that two string variable text1, text2 and an int variable count have been declared. Write statements to find the number ofstring containing substring "sport" and store this value in count count = 0;if (text1.Contains("sport")){count += 1;}if (text2.Contains("sport")){count += 1;}part 2min 3:45

Finding Position of Substrings

• When you need to know the position of the substring, you can use the IndexOf methods- It returns the integer position of substring's first occurrence, and returns -1 if not found. Common usages to find substrings are:• stringVar.IndexOf(substring): • stringVar.IndexOf(substring, start):• stringVar.IndexOf(substring, start, count):- It can also find characters; it returns the integer position of ch's first occurrence, and returns -1 if not found; common usages are:• stringVar.IndexOf(ch): • stringVar.IndexOf(ch, start):• stringVar.IndexOf(ch, start, count):- where start is an integer indicating the starting position for searching; count is an integer specifying the number of character positions to examine

IndexOf Substring Code Samples

for the cocoa beans example c# will start searching from the second cfor the xx oo example it will start at on the first o and it will stop searching at the last o due to it having a 8 count

IndexOf Character Code Samples 2

0

Finding Position of Substrings example

• What is the value of the int variable position after we execute the following statementsstring str = "I am a BAIS student.";int position = str.IndexOf("BAIS");• Answer: 7• What is the value of the int variable position after we execute the following statementsstring str = "I am a BAIS student.";int position = str.IndexOf("BAIS",8);• Answer: -1part 2min 19:45

Finding Position of Substrings example 2

• What is the value of the int variable position after we execute the following statementsstring str = "I am a BAIS student.";int position = str.IndexOf("BAIS",2);• Answer: 7• What is the value of the int variable position after we execute the following statementsstring str = "I am a BAIS student.";int position = str.IndexOf("BAIS",2,8);• Answer: -1part 2min 22:28

Finding Position of Substrings example 3

• What is the value of the int variable position after we execute the following statementsstring str = "I am a BAIS undergraduate student.";int position = str.IndexOf('a');• Answer: 2• What is the value of the int variable position after we execute the following statementsstring str = "I am a BAIS undergraduate student.";int position = str.IndexOf('a',8);• Answer: 19// c# is key sensitive so the capital A doesn't count for the small a.part 2min 24:45

Finding Position of Substrings example 4

• What is the value of the int variable position after we execute the following statementsstring str = "I am a BAIS undergraduate student.";int position = str.IndexOf('a',8,5);• Answer: -1• What is the value of the int variable position after we execute the following statementsstring str = "I am a BAIS undergraduate student.";int position = str.IndexOf('a',8,20);• Answer: 19part 2min 26:53

Finding Substring Position (Backwards)

• When you need to search backwards to find the LAST occurrence, you can use the LastIndexOf methods- It returns the index position of the last occurrence of a specified character or substring within this instance; common usages to find substrings are:• stringVar.LastIndexOf(substring): • stringVar.LastIndexOf(substring, start):• stringVar.LastIndexOf(substring, start, count):- It can also find characters; it returns the integer position of ch's first occurrence, and returns -1 if not found; common usages are:• stringVar.LastIndexOf(ch): • stringVar.LastIndexOf(ch, start):• stringVar.LastIndexOf(ch, start, count):- where start is an integer indicating the starting position for searching; count is an integer specifying the number of character positions to examine

LastIndexOf Substring Code Samples

for the first example, you are searching backwards so blue was found at index 11 first for the second example, you count 10 starting at the last x so you will start at oo and the first occurrence is at index 6

LastIndexOf Character Code Samples 2

0

The Substring Method

• When you need to retrieve a specific set of characters from a string, you can use the Substring method- stringVar.Substring(start): return a string containing the characters beginning at start, continuing to the end of stringVar- stringVar.Substring(start, count): return a string containing the characters beginning at start, continuing for count characters• where start is an integer indicating the starting position for searching, and count is an integer specifying the number of character positions to examine • Examples:

Finding Substring Position (Backwards) example

• What is the value of the string variable substr after we execute the following statementsstring str = "I am a BAIS undergraduate student.";string substr = str.Substring(20);Answer: substr = "duate student.";• What is the value of the string variable substr after we execute the following statementsstring str = "I am a BAIS undergraduate student.";string substr = str.Substring(20,5);Answer: substr = "duate";part 2min 36:17

Methods for Modifying a String

• To modify the contents of a string, you can use:- The Insert method to insert a string into another- The Remove method to remove specified characters from a string- The Trim method to remove all leading and trailing spaces from a string• Leading spaces are spaces before the string: " Hello"• Trailing spaces are spaces after the string: "Hello "- The TrimStart method to remove all leading spaces- The TrimEnd method to remove all trailing spaces- The ToLower and ToUpper methods to convert case

Methods for Modifying a String (Cont'd)

for the first example we are going to insert something before c

Methods for Modifying a String (Cont'd) 2

• The syntax of Trim methods are:stringVar.Trim()stringVar.TrimStart()stringVar.TrimEnd()• where stringVar is the name of a string variable

Methods for Modifying a String example

• Assume that we have declared a string variable as:string str = " hello ";• Write a statement to remove the all leading and trailing spaces from the string.• Answer: str = str.Trim();part 2min 44:05

Write the first line of an ifstatement that calls the char. Is-Upper method, passing a stringvariable named sentence and theindex value for the first character ofthe sentence variable as arguments.6

...

Write a statement that calls thechar.ToUpper method, passes achar variable named lowercaseas an argument, and stores the re-sult in a char variable named up.percase.7

...

What value does the char.To-Lower function return if the argu-ment is already lowercase?8

...

Write a statement that calls theStartsWith method of a stringnamed dessert, passes the string"strawberry"as an argument,and stores the result in a Booleanvariable named found.9

...

What value is returned by theIndexOf and LastIndexofmethods if the substring beingsearched for is not found?10

...

A program has two stringvariables named str1 and strz.Write a statement that trims theleading and trailing whitespacecharacters from the str1 variableand assigns the result to the strzvariable.11

...

A program has two stringvariables named vegetable andveggie. Write a statement that as-signs an all lowercase copy of thevegetable variable to theveggie variable.12

...

8.4 Tokenizing Strings

...

Tokenizing Strings

• When a string contains a series of words or other data separated by spaces or other characters, (e.g.: "apple:orange:banana"), the string can be thought to contain multiple items of data: apple, orange, and banana- Each item is known as a token- The character that separates tokens is known as a delimiter- The process of breaking a string into tokens is known as tokenizing• In C#, the Split method is used to tokenize strings- It extracts tokens from a string and returns them as an array of strings- You can pass null as an argument indicating white-spaces are delimiters- You can pass a character or char array as arguments to specify a list of delimiters

Tokenizing Strings example

Assume a string variable inputText has been declared and it equals a sequence of words separated by symbol ';' or ','. Write statements to transform the string to the same word sequence separated by space, i.e. ' '. For example, if the original value of inputText is "I;am,a;BAIS,student.", the transformed string should be "I am a BAIS student."Answer:char[] delim = {';', ',' }string[] token = inputText.Split(delim);string outputText = token[0];for (int index=1; index<token.Length; index++){outputText = outputText + " " + token[index];}Another answer:string outputText="";for (int index = 0; index<inputText.Length; index++){if ((inputText[index]==';')||(inputText[index]==',')){outputText = outputText + " ";}else{outputText = outputText + inputText[index];}}part 2min 48:45//Original string "I;am,a;BAIS,student"Token is an array of stringstoken [0] = "1";token[1] = "am";token[2] = "a";token[3] = "BAIS";token[4] = "student.";outputText = "I"; // 1After 1st iteration outputText = "I am"; // 2After 2nd iteration outputText = "I am a"; // 3After 3RD iteration outputText = "I am a BAIS"; // 4After 4th iteration outputText = "I am a BAIS student"; // 5

Tokenizing Strings example 2

0

Trimming a String Before Tokenizing

• If you don't trim the string before tokenizing and the user enters leading white-space characters, they will become part of the first token.• Use the Trim method to prevent leading and/or trailing white-space characters from being included in the first and last tokens.•str = str.Trim() will trim leading and trailing white-space characters from a string named str.

The following string containsthree tokens. What are they? Whatcharacter is the delimiter?"apples pears bananas"13

...

Look at the followingWhat value will be stored in x?What value will the first variablereference?14

0

Look at the following string:"/home/rjones/myda-ta.txt" Write code using the Splitmethod that can be used to extractthe following tokens from thestring: home, rjones, mydata, andtxt.15

...

Look at the following string:"dog$cat@bird&squirrel"。Write code using the Splitmethod that can be used to extractthe following tokens from thestring: dog, cat, bird, and squirrel.16

...

Declare a char array nameddelimiters and initialize it withthe comma and semicolon charac-ters.17

...

What delimiter is used to sep-arate data in a spreadsheet that hasbeen exported to a text file with the.csv file extension?18

...

8.5 The String.Format Method

...

The String.Format Method

• The String.Format method allows you to format and insert values into a string. • The generic form of the String.Format method is:String.Format(FormatString, Arg0, Arg1, Arg2...)where FormatString is the string to be formatted and Arg0, Arg1, etc. are the values that will be inserted into the string• This method returns a string with the specified values inserted into it

String.Format Method Examples

decimal sales = 1000m;string message = StringFormat("Our sales are {0} today.", sales);The String.Format method here takes two arguments. The format string is "Our sales are {0} today."The sales variable is argument 0The returned string will be:Our sales are 1000 today.

Formatting the Arguments

• You can optionally include a format specifier to format the argument as specified. For example:decimal amount = 123456789.45678m;string message = String.Format("The balance is {0:C}", amount);• The string that is returned will be:The balance is $123,456,789.46• There are many format specifiers available and are the same as those that can be used with the ToString method.

Specifying a Minimum Field Width

• The minimum field width is the minimum number of spaces that should be used to display the value. The example displays a floating-point number in a field that is 20 spaces wide:double number = 12345.6789;string message = String.Format("The number is: {0,20}", number);• The string that is returned will be:The number is: 12345.678900• The number itself takes up 12 spaces so the remaining 8 spaces are to the right of the number (after the colon)

Assume the following variabledeclaration exists in a program:double number1234567.456;Write a statement that uses theString. Format method to con-vert the value of the number vari-able to a string, formatted as:1,234,567.4619

...

Assume the following variabledeclaration exists in a program:double number= 123.456;Write a statement that uses theString.Format method to con-vert the value of the number vari-able to a string, rounded to onedecimal place, in a field that is 10spaces wide. (Do not use commaseparators.)20

...

Assume the following variabledeclaration exists in a program:Oint number=123456;Write a statement that uses theString. Format method to con-vert the value of the number vari-able to a string, in a field that is 10spaces wide, with comma separators.21

...

Assume the following variabledeclaration exists in a program:double number =123456.789;Write a statement that uses theString. Format method to con-vert the value of the number vari-able to a string, left-justified, withcomma separators, in a field that is20 spaces wide, rounded to twodecimal places.22

...