Разделы презентаций


NET.C#.0 7 Strings and Regular Expressions

What can we use ?2. Formatting expressions — using a couple of useful interfaces, IFormatProvider and IFormattable, and by implementing these interfaces on our own classes, we can actually define our

Слайды и текст этой презентации

Слайд 1NET.C#.07 Strings and Regular Expressions

NET.C#.07 Strings and Regular Expressions

Слайд 2What can we use ?
2. Formatting expressions — using a

couple of useful interfaces, IFormatProvider and IFormattable, and by implementing

these interfaces on our own classes, we can actually define our own formatting sequences, so we can display the values of our classes in whatever way we specify.

There are two types of string: String and StringBuilder

Building strings — If you’re performing repeated modifications on a string befor displaying it or passing it to some method, the String class can be very inefficient. For this kind of situation, another class, System.Text.StringBuilder is more suitable, since it has been designed exactly for this situation.

3. Regular expressions — .NET offers some classes that deal with the situation in which you need to identify or extract substrings that satisfy certain fairly sophisticated criteri. We can use some classes from System.Text.RegularExpressions, which are designed specifically to perform this kind of processing.

What can we use ?2. Formatting expressions — using a couple of useful interfaces, IFormatProvider and IFormattable,

Слайд 3System.String
System.String is a class that is specifically designed to

store a string, and allow a large number of operations

on the string.

Each string object is an immutable sequence of Unicode characters.
IT means that methods that appear to change the string actually return a modified copy; the original string remains intact in memory until it is garbage-collected.

1. string greetingText = “Hello from all the guys at GrSU “;

2. greetingText += “We do hope you enjoy this lesson ”;

1. An object of type System.String is created and initialized to hold the text. The .NET runtime allocates just enough memory to hold this text (32 chars)

2. We create a new string instance, with just enough memory allocated to store the combined text (55 chars). The old String object is now unreferensed.

System.String System.String is a class that is specifically designed to store a string, and allow a large

Слайд 4Declaration of string
// Simple declaration
string MyString = "Hello World";

// Strings

can include escape characters, such as \n or \t, which

// begin with a backslash character (\)
string Path2 = "c:\\Program Files";

// Using verbatim string literals, which start with the at (@)
// symbol.
string Path1 = @"c:\Program Files";

// Call the ToString( ) method on an object and assign the result to // a string
int myInteger = 235;
string integerString = myInteger.ToString();

// Empty string
string myString=String.Empty;




Declaration of string// Simple declarationstring MyString =

Слайд 5Manipulating Strings
The string class provides a host of methods for

comparing, searching, and manipulating strings, the most important of which

appear in Table:
Manipulating StringsThe string class provides a host of methods for comparing, searching, and manipulating strings, the most

Слайд 6Manipulating Strings
int result;
//compare two strings, case sensitive
result = string.Compare(s1, s2);

//

compare two strings, ignore case
result = string.Compare(s1, s2, true);

// insert

the word "excellent"
string s10 = s3.Insert(101, "excellent ");

// test whether a string ends with a set of characters
bool flag = s3.EndsWith("Training"));

// return the index of substring
int i = s3.IndexOf("Training");


Manipulating Stringsint result;//compare two strings, case sensitiveresult = string.Compare(s1, s2);// compare two strings, ignore caseresult = string.Compare(s1,

Слайд 7Splitting Strings
// create some strings to work with
string s1 =

"One,Two,Three Liberty Associates, Inc.";

// constants for the space and comma

characters
const char Space = ' ';
const char Comma = ',';

// array of delimiters to split the sentence with
char[] delimiters = new char[] { Space, Comma };

// split the string and then iterate over the resulting array of
// strings
foreach (string subString in s1.Split(delimiters))
{
Console.WriteLine(subString);
}

The result is array of strings

Splitting Strings// create some strings to work withstring s1 =

Слайд 8string object is an immutable
string returnNumber = "";
for (int i

= 0; i < 1000; i++)


returnNumber = returnNumber + i.ToString();
 

returnNumber = “0”
returnNumber = “1"
returnNumber = “12"
returnNumber = “123"
returnNumber = “1234”
returnNumber = “12345”
returnNumber = “123456”
. . .
returnNumber = “123456789…999”

 

Do you know when we do like that we are assigning it again and again?

Here we are defining a string called returnNumber and after that, in the loop we are concatenating the old one with the new.

It's really like assigning 999 new strings !!!

The problem is that the string type is not designed for this kind of operation. What
you want is to create a new string by appending a formatted string each time through the loop. The class you need is StringBuilder.


Слайд 9Dynamic Strings (class StringBuilder)
The System.Text.StringBuilder class is used for creating

and modifying strings.
Unlike String, StringBuilder is mutable.
The processing you can

do on a StringBuilder is limited to substitutions and appending or removing text from strings. However, it works in a much more efficient way.

When you construct a string, just enough memory gets allocated to hold the string. The StringBuilder, however, normally allocates more memory than needed

Dynamic Strings (class StringBuilder)The System.Text.StringBuilder class is used for creating and modifying strings.Unlike String, StringBuilder is mutable.The

Слайд 10StringBuilder
StringBuilder greetingBuilder = new StringBuilder(“Hello from all the guys at

Wrox Press. “, 150);
Then, on calling the Append() method, the

remaining text is placed in the empty space, without the need for more memory allocation.

greetingBuilder.Append(“We do hope you enjoy this book as much as we enjoyed writing it”);

Capacity

Normally, we have to use StringBuilder to perform any manipulation of strings, and String to store or display the final result.

StringBuilderStringBuilder greetingBuilder = new StringBuilder(“Hello from all the guys at Wrox Press. “, 150);Then, on calling the

Слайд 11StringBuilder members
The StringBuilder class has two main properties:
Length - indicates

the length of the string that it actually contains;
Capacity -

indicates the maximum length of the string in the memory allocation.

StringBuilder sb = new StringBuilder(“Hello”); //Length = 5

StringBuilder sb = new StringBuilder(20); //Capacity = 20

//we can set Capacity at any time
StringBuilder sb = new StringBuilder(“Hello”);
sb.Capacity = 100;

StringBuilder membersThe StringBuilder class has two main properties:Length - indicates the length of the string that it

Слайд 12StringBuilder members
The following table lists the main StringBuilder methods.

StringBuilder membersThe following table lists the main StringBuilder methods.

Слайд 13Regular Expressions
Regular expressions are Patterns that can be used to match

strings.
Regular expressions are a powerful language for describing and manipulating

text.
Regular expression is applied to a string—that is, to a set of characters. Often, that string is an text document.

With regular expressions, you can perform high-level operations on strings. For example, you can:

Identify all repeated words in a string (for example, “The
computer books books” to “The computer books”)

Convert all words to title case (for example, “this is a Title” to “This Is A Title”)

Convert all words to title case (for example, “this is a Title” to “This Is A Title”)

Separate the various elements of a URI (for example, given http://www.wrox.com, extract the protocol, computer name, file name, and so on)

Regular ExpressionsRegular expressions are Patterns that can be used to match strings.Regular expressions are a powerful language for

Слайд 14Regular Expressions
using System.Text;
using System.Text.RegularExpressions;
string text = Console.ReadLine();
string reg = @"^((([\w]+\.[\w]+)+)|([\w]+))@(([\w]+\.)+)([A-Za-z]{1,3})$";


if (Regex.IsMatch(text, reg)) Console.WriteLine("Email.");
else Console.WriteLine("Not email.");


Task: write

a C# console application that takes some text as an input, and determines if the text is an email address.

As you can see, a regular expression consists of two types of characters: literals and metacharacters.
A literal is a character you wish to match in the target string.
A metacharacter is a special symbol that acts as a command to the regular expression parser. The parser is the engine responsible for understanding the regular expression.

Regular Expressionsusing System.Text;using System.Text.RegularExpressions;string text = Console.ReadLine();string reg = @

Слайд 15Text: Anna Jones and a friend went to lunch


Regex: went
Matches: Anna Jones and a friend went

to lunch went

// to match the 'a' character followed by any two characters.
Text: abc def ant cow
Regex: a..
Matches: abc def ant cow

// matches 'a' followed by two word characters.
Text: abc anaconda ant cow apple
Regex: a\w\w
Matches: abc anaconda ant cow apple

// matches any three digits in a row
Text: 123 12 843 8472
Regex: \d\d\d
Matches: 123 12 843 8472

//matches any three char where the first character is 'd‘ or 'a'
Text: abc def ant cow
Regex: [da]..
Matches: abc def ant cow

Text:  Anna Jones and a friend went to lunch Regex:  went Matches: Anna Jones and

Слайд 16//matches any three characters where the second character is 'a',

'b', 'c' or 'd'.
Text: abc pen nda uml


Regex: .[a-d].
Matches: abc pen nda uml

//matches any of the characters from 'a' to 'z' or any digit from //'0' to '9' followed by two word characters.
Text: abc no 0aa i8i
Regex: [a-z0-9]\w\w (more simply [a-z\d])
Matches: abc no 0aa i8i

// matches the character 'a' followed by zero or more word
// characters.
Text: Anna Jones and a friend owned an anaconda
Regex: a\w*
Options: IgnoreCase
Matches: Anna Jones and a friend owned an anaconda

//matches any three characters where the second character is 'a', 'b', 'c' or 'd'. Text:  abc

Слайд 17Metacharacters and their Description

Metacharacters and their Description

Слайд 18Examples
using System;
using System.Text.RegularExpressions;

// First we see the input string.
string input

= "/content/alternate-1.aspx";
// Here we call Regex.Match.
Match match = Regex.Match(input, @"content/([A-Za-z0-9\-]+)\.aspx$",

RegexOptions.IgnoreCase);

// Here we check the Match instance.
if (match.Success)
{ // Finally, we get the Group value and display it.
string key = match.Groups[1].Value;
Console.WriteLine(key);
}
Examples using System;using System.Text.RegularExpressions;// First we see the input string.string input =

Слайд 19Thanks for Your Attention
By

Thanks  for Your AttentionBy

Обратная связь

Если не удалось найти и скачать доклад-презентацию, Вы можете заказать его на нашем сайте. Мы постараемся найти нужный Вам материал и отправим по электронной почте. Не стесняйтесь обращаться к нам, если у вас возникли вопросы или пожелания:

Email: Нажмите что бы посмотреть 

Что такое TheSlide.ru?

Это сайт презентации, докладов, проектов в PowerPoint. Здесь удобно  хранить и делиться своими презентациями с другими пользователями.


Для правообладателей

Яндекс.Метрика