1. Trang chủ
  2. » Giáo án - Bài giảng

Chapter 7 String, Char

6 233 0
Tài liệu được quét OCR, nội dung có thể không chính xác
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 6
Dung lượng 379,19 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Text = "Hai chudi gidng nhau"; else IbIKQ.Text = "Hai chuỗi khác nhau"; Locating characters and substrings > Example: > Finding the index of string or char in the other string, string[

Trang 1

String, Char

Chapter 7

Ebook: Beginning Visual C# 2010, chapter 5 Reference: C# How to Program, chapter 15

Declare and Initialing strings

| Used as a type: | string var_name; |

| string var_name = "value"; |

Example: string st = "Dai Hoc Cong Nghiep";

new string (char[] mang_ki_tu);

new String (char[] mang_ki_tu, int vi_tri_bat_dau, int

so_ki_tu);

new String (char ki_tu, int so_lan_lap);

Slide 3

String indexer, Length property

> String indexer

Retrieval of any character in the string (using [] operator)

> Length property

Returns the length of the string

> Example:

string st = "abc", output="";

for (int i=st.Length-1; i>=0; i )

output += st[i];

lblOutput Text = output;

Slide 5

Contents

> String class

> StringBuilder class

> Char class

Slide 2

Example:

Declare and Initialing strings string output;

string originalString,string| ,string2, string3, string4;

char[] characterArray = {'b'‘i,'r','c, ‘hd’, 'a,'y originalString = "Welcome to C# programming!";

string! = originalString;

string2 = new string( characterArray ); String Class ConstFUCEGES xi string3 = new string( characterArray, 6, 3 ); ( 7 string! = "Welcome to C# programming!"

string4= new string('C, 5 }; `) string2 = "birth day"

string3 = "day"

string4 = "CCCCC”

output = "stringl = ” + "\"" + string] + "V"\n" +

"string2 = "+ "V" + string2 + "V"\n" +

"string3 = "+ "V" + string3 + "V"\n" +

"string4 = "+ "V" + string4 + "V"\n";

MessageBox.Show( output, "String Class Constructors”, MessageBoxButtons OK, MessageBoxlcon.|nformation );

Slide 4

String comparing methods

> Compare (static method) Compares the values of two strings

Returns an integer value:

string | = string 2 > 0 string | > string 2 > | string | < string 2 > -I

> CompareTo (not static method)

Compares the current string object to another string

Returns an integer value (same as Compare method)

> Equals

Determines whether two strings are the same Returns true if two strings are the same

Slide 6

Trang 2

String comparing methods (cont) String checking methods

> StartsWith

Determines whether a string begins with the string passed, if yes, returns true

> EndsWith Determines whether a string ends with the string passed, if yes, returns true

> Example I:

string stl = "hello", st2 = "good bye’;

if (st|.CompareTo( st2 ) == 0)

1I xử lý hai chuỗi giống nhau

else if (stl.CompareTo( st2 ) > 0)

/ xử lý stl lớn hơn s2

else

> Example 2: Determines whether a string contains the string passed, if yes,

IbIKQ Text = "Hai chudi gidng nhau";

else IbIKQ.Text = "Hai chuỗi khác nhau";

Locating characters and substrings

> Example: > Finding the index of string (or char) in the other string, string[] strings = { "started", "starting", "ended", "ending" }; return -/ if not found

for ( int i = 0;i < strings.Length; i++ ) instance

output += strings[ i J; Returns the last occurence index of character or string in this

instance rtxOutput Text = " Strings starts with st:\n" + output;

Slide 9

Locating characters and substrings

in strings

> Example:

string letters = "abcdefghijklmabcdefghijklm";

rtxOutput.Text = letters + "\n";

rtxOutput.Text += ""c’ is located at index " + letters.lIndexOf( 'c' );

rtxOutput.Text += "\n";

rtxOutput.Text += "'a’ is located at index " + letters.IndexOf(‘a’,!);

rtxOutput.Text += "\n";

rtxOutput.Text += “Last ‘def’ is located at index " +

letters.LastIndexOf( "def" );

Slide 11

Slide 10

Characters trimming and rempving

StringS contents neyer

change

> Trim Removes white spaces from the beginning and end of a string

> TrimEnd

Removes characters specified in an array of characters from

the end ofa string

> TrimStart

Removes characters specified in an array of characters from

the beginning of a string

>» Remove Removes a specified number of characters from a specified

index position ina string

Slide 12

Trang 3

Miscellaneous String methods

› ToUpper

Converts all characters in a string to uppercase

› ToLower

Converts all characters ín a string to lowercase

› Format

Builds a formatted string from a set of input objects

Slide 13

Extracting substrings from strings

> Substring

Returns a substring from this instance

Substring (int startlndex, int length)

Substring (int startlndex)

> Example:

string sl = "Nguyen Thi Be Ba";

string s3;

txtName.Text = s!.Substring (11); if?

s3 = s|.Substring (0,s1.IndexOf ("") ); Hs3 =2,sl =?

sỈ = sI.Substring (sl.LastlndexOf (" ") + | ); isl =?

Slide 15

Concatenating strings

> Concat

Concatenating strings from two or more strings

Return a new string

Concat (String sI, String s2)

» You can use + operator to concat strings

> Example:

string string] = “Happy "5

string string2 = "Birthday";

IblOutput Text = String.Concat( string|, string2 );

Miscellaneous String methods

> Example:

string stl = “cheers!";

string st2 = "GOOD BYE";

IblHoa Text = stl ToUpper();

IbI Thuong Text = st2.ToLower();

Slide 14

Replacing strings

› Replace

Returns a string that replace all occurrences of this instance

by a new string or character

Replace (String oldValue, String newValue) Replace (char oldValue, char newValue)

> Example:

string string] = “cheers!";

// Replacing e with E in string | IblChuoilMoi lext = stringl.Replace( 'e, 'E' };

Slide 16

Split strings

> Split

Returns an array of strings, where each element is a word

Takes an array of chars that indicate which characters are to

be used as delimiters

> Example:

string words = "This is a list of words, with: a bit of punctuation”

+ "\tand a tab character.";

string[] arWords = words.Split(new Char] {'','7,°","", "\e });

foreach (string s in arWords ) {

if (s.TrimQ != "") Console.WriteLine(s);

Trang 4

Split strings (cont.)

This

is

a list

of words with

a bit

of punctuation

and

a tab character Slide 19

Contents

> String class

> StringBuilder class

> Char class

Slide 21

Append and AppendFormat methods

> Append method

Allow various data-type values to append to the end of a

StringBuilder

Convert argument into string

>» AppendFormat method

Convert string to a specifiable format

Split strings (cont.)

> Example: Split a name

string sl =“Nguyén Van An";

string[] s;

s = s|.Split (new char[]f' }); //tham so truyen la mang ky tu

txtHo.Text = s[0];

txtTen.Text = s[s.Length-1];

for (int i=l; i<s.Length-2; i++)

{

txtHolot.Text += s[i] + ““;

}

Slide 20

StringBuilder class

> StringBuilder class

Create and manipulate dynamic string information

Capable of resizing

Belongs to namespace System.Text

> Objects of class String are constant strings (fixed length and

value), whereas object of class StringBuilder are mutable strings so you can add, delete, replace characters in the objects

Slide 22

Example: Append method

object objectValue = “hello”;

string stringValue = “good bye";

char[] characterArray = { 2, b,'c,'dý, 'evf

bool booleanValue = true;

char characterValue = 'Z';

int integerValue = 7;

long longValue = | 000000;

float floatValue = 2.5F;

double doubleValue = 33.333;

StringBuilder buffer = new StringBuilder ();

// use method Append to append values to buffer bufferAppend( objectValue );

bufer.Append(” ”);

bufferAppend( stringValue );

bufer.Append(” ”);

bufferAppend( characterArray );

bufer.Append(” ”);

Trang 5

Example: Append method (cont.)

buffer Append( characterArray, 0, 3 );

bufferAppend(" ");

buffer Append( booleanValue );

bufferAppend(" ");

buffer.Append(” ” };

buffer Append( integerValue );

bufferAppend(" ");

buffer.Append(longValue );

bufferAppend(" ");

buffer Append( float Value );

bufferAppend(" ");

buffer Append( doubleValue );

=

YD buffer =hello goodbye abcdef abc True Z 7 1000000 2.5 33,333

MessageBox.Show( "buffer = " + buffer ToString(), "Demonstrating StringBuilder append

method,MessageBoxButtons, Ol, MessageBoxlcon.|nformation );

Slide 26

Example: AppendFormat method

/! formatted string

string2 = "Number:{0:d3}.\n" + "Number right aligned with

spaces:{0, 4}.\n" + "Number left aligned with spaces:{0, -4}.";

// append to buffer formatted string with argument

buffer.AppendFormat( string2, 5 );

// display formatted strings

MessageBox.Show( buffer ToString(), “Using AppendFormat’,

MessageBoxButtons.O, MessageBoxlcon.|nformation );

Using appendFormat xi

2 This car costs: $1,234.56,

`) Number:005,

Number right aligned with spaces: 5, Number left aligned with spaces:5

Example: Insert, Remove method

object objectValue = “hello”;

string stringValue = “good bye";

char[] characterArray = {'a,'b,'c, d,'e,'f}

bool booleanValue = true;

char characterValue = ‘|’;

int integerValue = 7;

long longValue = | 0000000;

float floatValue = 2.5F;

double doubleValue = 33.333;

StringBuilder buffer = new StringBuilder();

string output;

// insert values into buffer

buffer.Insert(0, objectValue);

buffer.Insert(O,” ");

Slide 30

Example: AppendFormat method

StringBuilder buffer = new StringBuilder();

string stringl, string2;

If chuỗi định dạng string] = "This {6} costs:{l:C}.\n”)

// stringl argument array object[] objectArray = new object[ 2 ];

objectArray[ 0 ] = "car";

objectArray[ | ] = | 234.56;

// append to buffer formatted string with argument buffer.AppendFormat( stringl, objectArray );

Slide 27

Insert, Remove and Replace methods

> Insert method

Insert into at any position

Program may throw ArgumentOutOfRangeException

>» Remove method

Takes two argument

Program may throw ArgumentOutOfRangeException

› Replace method Substitute specified string

Slide 29

Example: Insert, Remove method

buffer.Insert(0, stringValue);

buffer.Insert(0," ");

buffer.Insert(0, characterArray);

buffer.Insert(0," ");

buffer.Insert(0, booleanValue);

buffer.Insert(0," ");

buffer.Insert(0, characterValue);

buffer.Insert(0,” ");

buffer.Insert(0, integer Value);

buffer.Insert(0," ");

buffer.Insert(0, longValue);

buffer.Insert(0," ");

buffer.Insert(0, floatValue);

buffer.Insert(0," ");

buffer.Insert(0, doubleValue);

buffer.Insert(0,.".");

Slide 31

Trang 6

Example: Insert, Remove method

output = "buffer after inserts: \n" + buffer ToString() + "\n\n"; > buffer =?

bufferRemove( | 0,! );// delete 2 in 2.5

buffer.Remove( 2, 4); // delete 333 in 33.333

output += "buffer after Removes:\n" + buffer.ToString); = > buffer =?

MessageBox.Show( output, "Demonstrating StringBuilder” + "Insert and Remove

methods",MessageBoxButtons, Ol, MessageBoxlcon.!nformation );

TSM eee momen uli g sy ons xị

{ i buffer after inserts:

1) 33,333 2.5 10000000 7 K True abcdef good bye hello

buffer after Removes:

33 ,5 10000000 7 K True abcdef good bye hello

Slide 32

Example: Replace method

MessageBox.Show( output, “Using StringBuilder method Replace",

MessageBoxButtons.O, MessageBoxlcon./nformation );

Using StringBuilder method Replace ye |

( 3 Before replacements:

1) Happy Birthday Jane

good bye greg After replacements:

Happy Birthday Greg Good bye greg

Slide 34

Char methods

> IsLower

> IsUpper

> ToUpper

> ToLower

> IsPunctuation

> IsSymbol

> IsWhiteSpace

Slide 36

Example: Replace method

StringBuilder builder! = new StringBuilder( “Happy Birthday Jane" );

StringBuilder builder2 = new StringBuilder( “good bye greg" );

string output = “Before replacements:\n" + builder|.ToString) + “\n" + builder2.ToString();

/ithay Jane bang Greg trong chudi builder |

builder | Replace( “Jane”, "Greg" );

Iithay g bang G trong chuỗi builder2 từ vị trí 0,trong 5 ký tự đầu

builder2.Replace( 'z, G',0, 5 );

output += ”\nìnAfter replacements:\n” + builder |.ToStringQ + “\n" + builder2.ToString();

Slide 33

Contents

> String class

> StringBuilder class

> Char class

Slide 35

EES lolx Ermer o.choracter, fa

Example: Char methods

char character = Convert.ToChar(inputTextBox Text );

string output;

output = “is digit:" + CharlsDigit(inputCharacter ) + "\r\n";

output += “is letter:” + Char.lsLetter(inputCharacter ) + "\r\n"5

output += “is letter or digit:” + CharlsLetterOrDigit(inputCharacter ) + "\r\n"; output += "is lower case:" + Char.lsLower(inputCharacter ) + "\r\n";

output += "is upper case: " + Char.lsUpper(inputCharacter ) + "\r\n";

output += "to upper case:" + Char ToUpper(inputCharacter ) + “\r\n";

output += "to lower case:" + Char ToLower(inputCharacter ) + "\r\n";

output += "is punctuation:" + Char.lsPunctuation(inputCharacter ) + "\r\n";

output += "is symbol:" + Char.IlsSymbol(inputCharacter );

output TextBox Text = output;

Slide 37

Ngày đăng: 13/05/2014, 11:31

TỪ KHÓA LIÊN QUAN