Docsity

Introduction to String and Character Processing in .NET Framework Class Library, Slides of Information Technology

Toggle sidebar
bg1
101
Mahmoud Hilal Farhan College Of Computer Sciences &
Information Technology – University Of AL Anbar
CHAPTER FIVE
STRINGS, CHARACTERS, REGULAR
EXPRESSIONS, STRUCTURES AND
ENUMERATIONS
5.1 Introduction
This chapter introduces the .NET Framework Class Library’s string
-
and character-processing ca pabilities and demonstrates how to use regular
expressions to search for patterns in text. The techniques it presents can be
employed in text editors, word processors, page layout software,
computerized typesetting systems and other kinds of text-processing
software.
We discuss regular expressions. We present classes Regex and Match
from the System.Text.RegularExpressions namespace as well as the symbols
that are used to form regular expressions. Finally, we introduce to structures
and enumerations and using them in C# Language.
5.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. In addition to normal characters, a
progr am also can contain character constants. 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 accor ding to the Unicode character set, an
international character set that contains many more symbols and letters than
does the ASCII character set.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Introduction to String and Character Processing in .NET Framework Class Library and more Slides Information Technology in PDF only on Docsity!

Mahmoud Hilal Farhan 101 College Of Computer Sciences &

Information Technology – University Of AL Anbar

CHAPTER FIVE

STRINGS, CHARACTERS, REGULAR

EXPRESSIONS, STRUCTURES AND

ENUMERATIONS

5.1 Introduction

This chapter introduces the .NET Framework Class Library’s string -

and character-processing capabilities and demonstrates how to use regular

expressions to search for patterns in text. The techniques it presents can be

employed in text editors, word processors, page layout software,

computerized typesetting systems and other kinds of text-processing

software.

We discuss regular expressions. We present classes Regex and Match

from the System.Text.RegularExpressions namespace as well as the symbols

that are used to form regular expressions. Finally, we introduce to structures

and enumerations and using them in C# Language.

5.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. In addition to normal characters, a

program also can contain character constants. 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.

Mahmoud Hilal Farhan 102 College Of Computer Sciences &

Information Technology – University Of AL Anbar

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 string in the

System namespace. We write string literals, also called string constants, as

sequences of characters in double quotation marks, as follows:

A declaration can assign a string literal to a string reference. The declaration

color = ;

initializes string reference color to refer to the string literal object "blue". 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. Backslashes within the double quotation marks

following the @ character are not considered escape sequences, but rather

regular backslash characters. Often this simplifies programming and makes

the code easier to read. For example, consider the string

"C:\MyFolder\MySubFolder\MyFile.txt" with the following assignment:

file = ;

Using the verbatim string syntax, the assignment can be altered to

file = @ ;

This approach also has the advantage of allowing string literals to span

multiple lines by preserving all newlines, spaces and tabs.

Mahmoud Hilal Farhan 104 College Of Computer Sciences &

Information Technology – University Of AL Anbar

The third argument specifies the number of characters (the count) to

be copied from the specified starting position in the array. The new string

contains a copy of the specified characters in the array. Line 16 assigns to

string4 a new string, using the string constructor that takes as arguments a

character and an int specifying the number of times to repeat that character

in the string.

5.4 string Indexer, Length Property and CopyTo Method

The application in Fig. 5.2 presents the string indexer, 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.

1 // Fig. 5.2: StringMethods.cs

2 // Using the indexer, property Length and method CopyTo

3 // of class string.

4 System;

6 StringMethods

8 Main( [] args )

10 string1 = ;

11 [] characterArray = char[ ];

13 // output string

14 Console.WriteLine( + string1 + );

16 // test Length property

17 Console.WriteLine( + string1.Length );

19 // loop through characters in string1 and display reversed

20 Console.Write( );

22 ( i = string1.Length^ - ; i >= ; i-- )

23 Console.Write(

string1[ i ] );

25 // copy characters from string1 into characterArray

26 string1.CopyTo( 0, characterArray, 0, characterArray.Length );

27 Console.Write( );

29 ( i = ; i < characterArray.Length; i++ )

30 Console.Write(

characterArray[ i ] );

32 Console.WriteLine( );

33 } // end Main

34 } // end class StringMethods

Mahmoud Hilal Farhan 105 College Of Computer Sciences &

Information Technology – University Of AL Anbar

string1: "hello there"

Length of string1: 11 The string reversed is: ereht olleh The character array is: hello

Fig. 5.2 |string indexer, Length property and CopyTo method.

This application determines the length of a string, displays its

characters in reverse order and copies a series of characters from the string

to a character array. Line 17 uses string property Length to determine the

number of characters in string1. Like arrays, strings always know their own

size. Lines 22– 23 write the characters of string1 in reverse order using the

string indexer. The string indexer treats a string as an array of chars and

returns each character at a specific position in the string. The indexer

receives an integer argument as the position number and returns the

character at that position. As with arrays, the first element of a string is

considered to be at position 0.

Line 26 uses string method CopyTo to copy the characters of string

into a character array (characterArray). The first argument given to method

CopyTo is the index from which the method begins copying characters in the

string. The second argument is the character array into which the characters

are copied. The third argument is the index specifying the starting location

at which the method begins placing the copied characters into the character

array. The last argument is the number of characters that the method will

copy from the string. Lines 29– 30 output the char array contents one

character at a time.

(^) 5.5 Comparing strings

The next two examples demonstrate various methods for comparing

strings. To understand how one string can be “greater than” or “less than”

another, consider the process of alphabetizing a series of last names. The

reader would, no doubt, place "Jones" before "Smith", because the first

letter of "Jones" comes before the first letter of "Smith" in the alphabet. The

alphabet is more than just a set of 26 letters—it’s an ordered list of

characters in which each letter occurs in a specific position. For example, Z

is more than just a letter of the alphabet; it’s specifically the twenty -sixth

letter of the alphabet..

Mahmoud Hilal Farhan 107 College Of Computer Sciences &

Information Technology – University Of AL Anbar

32 // test for equality comparing case

33 ( string.Equals( string3, string4 ) ) // static method

34 Console.WriteLine( );

36 Console.WriteLine( );

38 // test CompareTo

39 Console.WriteLine( +

40 string1.CompareTo( string2 ) + +

42 string2.CompareTo( string1 ) + +

44 string1.CompareTo( string1 ) + +

46 string3.CompareTo( string4 ) +

48 string4.CompareTo( string3 ) + );

49 } // end Main

50 } // end class StringCompare

Fig. 5.3 |string test todetermineequality.

The condition in line 27 uses the overloaded equality operator (= =) to

compare string string1 with the literal string "hello" for equality. In C#, the

equality operator also compares the contents of two strings. Thus, the

condition in the if statement evaluates to true, because the values of string

and "hello" are equal.

Line 33 tests whether string3 and string4 are equal to illustrate that

comparisons are indeed case sensitive. Here, static method Equals is used to

compare the values of two strings. "Happy Birthday" does not equal "happy

birthday", so the condition of the if statement fails, and the message "string

does not equal string4" is output (line 36).

Mahmoud Hilal Farhan 108 College Of Computer Sciences &

Information Technology – University Of AL Anbar

Lines 40 – 48 use string method CompareTo to compare strings.

Method CompareTo returns 0 if the strings are equal, a negative value if the

string that invokes CompareTo is less than the string that’s passed as an

argument and a positive value if the string that invokes CompareTo is

greater than the string that’s passed as an argument. Notice that

CompareTo considers string3 to be greater than string4. The only difference

between these two strings is that string3 contains two uppercase letters in

positions where string4 contains lowercase letters.

Determining Whether a String Begins or Ends with a Specified String

Figure 5.4 shows how to test whether a string instance begins or ends

with a given string. Method StartsWith determines whether a string instance

starts with the string text passed to it as an argument. Method EndsWith

determines whether a string instance ends with the string text passed to it as

an argument. Class stringStartEnd’s Main method defines an array of

strings (called strings), which contains "started", "starting", "ended" and

"ending". The remainder of method Main tests the elements of the array to

determine whether they start or end with a particular set of characters.

Line 13 uses method StartsWith , which takes a string argument. The

condition in the if statement determines whether the string at index i of the

array starts with the characters "st". If so, the method returns true, and

strings[i] is output along with a message.

1 // Fig. 5.4: StringStartEnd.cs

2 // Demonstrating StartsWith and EndsWith methods.

3 System;

5 StringStartEnd

7 Main( [] args )

9 [] strings = { , , , };

11 // test every string to see if it starts with "st"

12 ( i = ; i < strings.Length; i++ )

13 ( strings[ i ].StartsWith( ) )

14 Console.WriteLine( + strings[ i ] + +

17 Console.WriteLine();

Mahmoud Hilal Farhan 110 College Of Computer Sciences &

Information Technology – University Of AL Anbar

1 // Fig. 5.5: StringIndexMethods.cs

2 // Using string-searching methods.

3 System;

5 StringIndexMethods

7 Main( [] args )

9 letters = ;

10 [] searchLetters = { , , };

12 // test IndexOf to locate a character in a string

13 Console.WriteLine( +

14 letters.IndexOf( ) );

15 Console.WriteLine( +

16 letters.IndexOf( , ) );

17 Console.WriteLine( +

letters.IndexOf( , , ) );

20 // test LastIndexOf to find a character in a string

21 Console.WriteLine( +

22 letters.LastIndexOf( ) );

23 Console.WriteLine( +

24 + letters.LastIndexOf( , ) );

25 Console.WriteLine( +

letters.LastIndexOf( , , ) );

28 // test IndexOf to locate a substring in a string

29 Console.WriteLine( +

30 letters.IndexOf( ) );

31 Console.WriteLine( +

32 + letters.IndexOf( , ) );

33 Console.WriteLine( +

35 letters.IndexOf( , , ) );

37 // test LastIndexOf to find a substring in a string

38 Console.WriteLine( +

39 letters.LastIndexOf( ) );

40 Console.WriteLine( +

41 + letters.LastIndexOf( , ) );

42 Console.WriteLine( +

44 letters.LastIndexOf( , , ) );

46 // test IndexOfAny to find first occurrence of character in array

47 Console.WriteLine( +

48 + letters.IndexOfAny(^ searchLetters^ )^ );

49 Console.WriteLine( +

50 + letters.IndexOfAny( searchLetters, ) );

51 Console.WriteLine( +

53 letters.IndexOfAny( searchLetters, , ) );

Mahmoud Hilal Farhan 111 College Of Computer Sciences &

Information Technology – University Of AL Anbar

55 // test LastIndexOfAny to find last occurrence of character

56 // in array

57 Console.WriteLine( +

58 + letters.LastIndexOfAny( searchLetters ) );

59 Console.WriteLine( +

61 letters.LastIndexOfAny( searchLetters, ) );

62 Console.WriteLine( +

64 letters.LastIndexOfAny( searchLetters, , ) );

65 } // end Main

66 } // end class StringIndexMethods

Fig. 5.5 |Searchingfor charactersandsubstrings instrings.

Lines 22, 24 and 26 use method LastIndexOf to locate the last

occurrence of a character in a string. Method LastIndexOf performs the

search from the end of the string to the beginning of the string. If it finds the

character, LastIndexOf returns the index of the specified character in the

string; otherwise, LastIndexOf returns – 1. There are three versions of

method LastIndexOf. The expression in line 22 uses the version that takes as

an argument the character for which to search. The expression in line 24

uses the version that takes two arguments— the character for which to search

and the highest index from which to begin searching backward for the

character. The expression in line 26 uses a third version of method

LastIndexOf that takes three arguments— the character for which to search,

the starting index from which to start searching backward and the number of

Mahmoud Hilal Farhan 113 College Of Computer Sciences &

Information Technology – University Of AL Anbar

The first argument specifies the starting index from which the method

copies characters from the original string. The second argument specifies

the length of the substring to copy. The substring returned contains a copy of

the specified characters from the original string.

5.8 Concatenating strings

The + operator is not the only way to perform string concatenation.

The static method Concat of class string (Fig. 5.7) concatenates two strings

and returns a new string containing the combined characters from both

original strings. Line 16 appends the characters from string2 to the end of a

copy of string1, using method Concat. The statement in line 16 does not

modify the original strings.

1 // Fig. 5.7: SubConcatenation.cs

2 // Demonstrating string class Concat method.

3 System;

5 StringConcatenation

7 Main( [] args )

9 string1 = ;

10 string2 = ;

12 Console.WriteLine( + string1 + +

13 + string2 + );

14 Console.WriteLine(

16 string.Concat( string1, string2 ) );

17 Console.WriteLine( + string1 );

18 } // end Main

19 } // end class StringConcatenation

string1 = "Happy "

string2 = "Birthday" Result of string.Concat( string1, string2 ) = Happy Birthday string1 after concatenation = Happy

Fig. 5.7 |Concat static method.

Mahmoud Hilal Farhan 114 College Of Computer Sciences &

Information Technology – University Of AL Anbar

5.9 Miscellaneous string Methods

Class string provides several methods that return modified copies of

strings. The application in Fig. 5.8 demonstrates the use of these methods,

which include string methods Replace, ToLower, ToUpper and Trim.

1 // Fig. 5.8: StringMethods2.cs

2 // Demonstrating string methods Replace, ToLower, ToUpper, Trim,

3 // and ToString.

4 System;

6 StringMethods

8 Main( [] args )

10 string1 = ;

11 string2 = ;

12 string3 = ;

14 Console.WriteLine( + string1 + +

15 + string2 + +

16 + string3 + );

18 // call method Replace

19 Console.WriteLine(

21 string1.Replace( , )

23 // call ToLower and ToUpper

24 Console.WriteLine( +

25 string1.ToUpper()

26 string2.ToLower()

28 // call Trim method

29 Console.WriteLine( +

30 string3.Trim() +^ );

32 Console.WriteLine( );

33 } // end Main

34 } // end class StringMethods

Fig. 5.8 |string methods Replace, ToLower, ToUpper and Trim.