Вы находитесь на странице: 1из 18

String Manipulation in C# .

NET
Quite often, strings of text need manipulating. Data from a textbox need to be tested and checked for things like blank strings, capital letters, extra spaces, incorrect formats, and a whole lots more besides. Data from text files often needs to be chopped and parsed before doing something with it, and the information your get from and put into databases routinely needs to be examined and worked on. All of this comes under the general heading of String Manipulation. Later in this section, you re going to be creating your !ery own "angman programme. #he programme will make use of string manipulation techni$ues. Let s go through a few of the things that will help you deal with strings of text.

C# String Variables
%ou !e already worked with string !ariables a lot in this book. &ut there s a lot more to them than meets the eye. Strings come with their own Methods and 'roperties that you can make use of. #o see which Methods and 'roperties are a!ailable, start a new () *indows Application. Add a button and a textbox to your form. +or the textbox, change the #ext property to ,some text, -make sure the text is in lowercase.. /ow Double click your button to get at the coding window. #hen enter the following string declaration string stringVar = textBox1.Text; 0n a new line, type the following1 textBox1.Text = stringVar. As soon as you type the full stop at the end, you ll see the 2ntelliSense list appear1

2ntelliSense is showing you a list of Methods and 'roperties that are a!ailable for this string ob4ect you ha!e called stringVar. "ere s a fuller list1

#here s actually one 'roperty on the list. &ut it s one you use a lot, and we ll see it in action later. Most of the Methods on the list you won t use at all, and a lot of them are 4ust plain baffling5 Some are $uite ob!ious in what they do, though. Select ToUpper from the list by double clicking it. &ecause it s a Method, you need some round brackets. #ype a left round bracket and you ll see a yellow box appear, gi!ing you the a!ailable options for this Method. +or the #o6pper Method, there are only two options a!ailable1

%ou can press the Down arrow on your keyboard to see the other one. &ut the first one, 3 of 7, is the one we need. As the tool tip is telling you, this Method con!erts the string to upper case. -#he current culture it is talking about is which language you re typing in1 a symbolic language like (hinese or 8apanese will ha!e different grammatical rules than 9nglish.. #he round brackets of the Method are empty, meaning it doesn t take any arguments. So 4ust type the right round bracket, followed by a semicolon to end the line. %our code should look like this1

/ow run your programme. *hen the form starts it will look like this1

After you click the button, () runs the #o6pper Method and con!erts the text in the text box to uppercase1

Another Method that changes case is the #oLower Method. #his is the opposite of #o6pper, and is used in the same way.

Trim Unwante C!ara"ters in C# .NET


2f you ha!e another look at the Method list, you ll see that there are three that deal with #rimming1 #rim, #rim9nd and #rimStart. #hese methods can be used to #rim unwanted characters from strings. Add another button to your form. %ou can change the #ext property of your buttons. 9nter the text ,6ppercase, for the first one. +or the new button, enter #rim for the text property. Add another text box below the first one and set the #ext property as follows1 # Trimming # Lea!e out the double $uotes but tap the spacebar on your keyboard three times before you type the text. At the end of the text, tap the spacebar three more times. %our +orm should then look like this1

#he line in the second text box is where the cursor is. /ow double click your second button to get at the code. *e can count the number of characters a string has with the Length property. 9nter the following code for your button1 ;

#he first line 4ust gets the text from the text box and puts it into a !ariable called stringTrim. "a!e a look at the second line, though1 int stringLength < string#rim.$engt!= *e !e set up a new integer !ariable called string$engt!. #o get the length of a string, type a dot after your string !ariable name. +rom the 2ntelliSense list, select the $engt! property. /ote that you don t need any round brackets, because it s a property not a method. #he Length of a string, by the way, refers to how many characters is in the string. #he third line uses a Message&ox to display the result1 MessageBox.S!ow% stringLength.#oString-. &; %ou !e seen the #oString method before. #his can be used to con!ert numbers to a string a text. So ,3>, instead of 3>. -#he double $uotes mean it s text. *ithout the $uotes, it s a number. #he !ariable called stringLength will hold a number.. ?un your programme and click the #rim button on your form. #he message box should display an answer of 3;. #he word ,#rimming,, howe!er, only has @ characters in it. #he other A are the three spaces we put at the beginning and end of the word. #o get rid of space at the beginning and end of text, you can use the #rim method. Add the following line of code to your button1

#he code to add is highlighted, in the image abo!e. 2t s this1

string#rim < string#rim.Trim%&= So after the dot of the stringTrim !ariable, you select the Trim method from the 2ntelliSense list, followed by a pair of empty round brackets. ?un your programme and click the button again. %ou should find that the length is now @. So #rim has trimmed the blank spaces from the beginning and the end of our word. 2f you only wanted to trim the blank spaces at the end of the word, or 4ust the blank spaces at the beginning of the word, you can use #rim9nd and #rimStart1 string#rim < string#rim.TrimStart% null &= #rimStart and #rim9nd are supposed to take a character array as a parameter. 2f you type the keyword null instead, it will trim the white space -blank characters.. 8ust as a reference for you, here s some code that strips unwanted hyphens off the end of a string1

#he trimC!ar line is a character array - "!arC D . with the hyphen in between curly brackets. #his is then handed to the #rim9nd method as a parameter.

2n the next lesson, we ll take a look at the Contains method.

T!e Contains Met!o in C# .NET


#he contains method can be used if you want to check if a string contains certain characters. 2t s fairly simple to use. "ere s an example1

After the contains method, you type a pair of round brackets. 2n between the round brackets, you type the text you re checking for. 2n our code, we re using an if statement. 2f it s true that the string contains a ,E, character, then some code can be executed.

A more complicated, and probably more useful, method that you ll need to know about is called'n ex(). #hat s the next lesson.

T!e 'n ex() Met!o in C# .NET


#he 'n ex() method can be used to check if one character is inside of another. +or example, suppose you want to check an email address to see if it contains the F character. 2f it doesn t you can tell the user that it s an in!alid email address. Add a new button and a new text box to your form. +or the #ext property of the text box, enter an email address, complete with F sign. Double click your button to get at the code. 9nter the following1

#he first thing to examine is how 'n ex() works. "ere s the line of code1 int result < string9mail.'n ex()% ,F, &= #he 2ndex0f method returns an integer. #his number is the character s position in the word you re trying to check. 2n the code abo!e, we want to check the word that s inside of the !ariable we !e calledstringEmail. *e want to see if it contains the ,F, character. #his goes between the round brackets of 2ndex0f. 2f () finds the character, it will tell you where it was -at position number : in the word , for example.. #his number is then stored inside of the int !ariable we !e called result. 2f the character you re looking for can t be found, 2ndex0f will return a !alue of E3 -minus 3.. #he 2+ statement in our code checks the !alue of the result !ariable, to see what s inside of it. 2f it s E3 display an, 2n!alid 9mail Address message,= 2f it s not E3, a different message is displayed. ?un your programme and click the button. "ere s the form with an F character in the text box1

And here s what happens when we delete the F character from the text box1 @

/ote that the first message box displays ,F found at position 7,. 2f you look at the email address in our text box, howe!er, it s me*me."om. So you might be thinking that the F character is at position :, not 7. 2f () were to start counting at 3, you d be right. &ut it doesn t. *hen you use the 2ndex0f method, the count starts at Hero. %ou can also specify a start position, and a character count for a search. #his is useful if you want to do things like checking a longer string and counting how many occurrences there are of a particular character or characters. 0r if you want a simple check to see if, say, a website entered in a text box on your form begins with http1IIwww. "ere s some code that does 4ust that1

"a!e a look at this part of the highlighted line1 webAddress.'n ex()% check*ebAddress, start, num0f(hars &

#his time, we ha!e three parameters inside of the round brackets of 2ndex0f. #he first one is the string we want to check -"!e"+,eb- ress.. #hen we ha!e start, and num()C!ars. #he start !ariable is where in your full string -webAddress. you want to start checking. #he third parameter, num0f(hars, is the number of characters you want to check from that starting position. 2n our code, the start is > and the number of characters is 3>. And finally, for 2ndex0f, here s some code that checks a long string of text and counts how many times the word true appears1

#he code is a bit complex, so don t worry if you don t understand it all. &ut it s 4ust using 2ndex0f with three parameters1 the word to search for, a starting position, and how many characters you want to check. #he start position changes when the word is found= and the number of characters to count shrinks as you mo!e through the word.

3>

T!e 'nsert Met!o in C# .NET


#he 2nsert method is, not surprisingly, used to insert characters into a string of text. %ou use it like this1 string someText = #Some Text#; someText = someText.'nsert% ./ #More # &; 2n between the round brackets of 2nsert, you need two things1 A position in your text, and the text you want to insert. A comma separates the two. 2n our code abo!e, the position that we want to insert the new text is where the # of ,#ext, currently is. #his is the fifth character in the string -the count starts at Hero.. #he text that we want to 2nsert is the word ,More,.

Exer"ise #est out the code abo!e, for the 2nsert- . method. "a!e one message box to display the old text, and a second message box to display the new text.

0a $e)t an 0a 1ig!t
#he 'adLeft and 'ad?ight methods in () can also be used to insert characters. &ut these are used to add characters to the beginning and end of your text. As an example, add a new button to your form, and a new text box. +or the text box, set the #ext property to ,'ad Left,. Double click your button and enter the following code1 string pa pa ing$e)t = textBox..Text; ing$e)t.0a $e)t% 23 &; ing$e)t;

ing$e)t = pa

textBox..Text = pa

#he 'adLeft and 'ad?ight methods can take 3 or two parameters. *e re 4ust using 3. #his will insert blank space characters to the start of the string. #he total number of characters will be 7>. So, if you ha!e four characters in the text box, 'adLeft-7>. will add 3A blank spaces, making a total of 7> characters in the text box after the button is clicked. ?un your programme and test it out. #ype the text ,'ad Left, in the text box. %our text box should look like this before the button is clicked1

33

And it will look like this after you click the button1

2f you don t want to pad with blank spaces, you can use the second parameter. #his is the character you want to pad with1 pa ing$e)t = pa ing$e)t.0a $e)t%23 / 454&;

2n the code abo!e, we re telling () to pad with the asterisk character, instead of the default blank spaces. -/ote the use of the single $uotes surrounding the 5 character. () doesn t seem to like you using double $uotes, if the type is char.. 2f you change your code to the one abo!e, then click the button on your form, the result will be this1

2f you want to add characters to the end of the string, use 'ad?ight instead of 'adLeft.

1emo6e an 1epla"e in C# .NET


!e 1emo6e Met!o
As its name suggests, this method is used to ?emo!e characters from a string of text. "ere s a simple example of its use1 string ol String = #some text text text#; MessageBox.S!ow%ol String&; string newString = ol String.1emo6e%13/ 7&; MessageBox.S!ow%newString&; ?emo!e takes two parameters. #he first one is what position in your string you want to start at. -#he count starts at Hero.. #he second parameter is how many characters you want to delete, starting from the position you specified. Add another button to your form and try out the code abo!e. 37

T!e 1epla"e Met!o


#he ?eplace method, you won t be surprised to hear, can be used to replace characters in your string. "ere s an example of its use1 string spellingError = #mista+#; spellingError = spellingError.1epla"e%spellingError/ #mista+e#&; #he ?eplace method takes two parameters, the old word and the new word. 2n the code abo!e, we re replacing ,mistak, with ,mistake,.

Substring in C# .NET
#he Substring method is used to grab characters from a string of text. +or example, suppose you were testing an email address. %ou want to test the last four characters to see they are .com. %ou can use Substring to return 4ust those four characters, and see what s in them. -%ou can also use 2ndex0f to achie!e the same result.. Substring has this syntax1 t!e8wor .Substring% start8position & So the word you want to grab characters from goes first, followed by the Substring method. 2n between the round brackets, you ha!e to tell () where in the word to start grabbing characters from. &ut Substring can also take a second parameter1 t!e8wor .Substring% start8position/ num8o)8"!ars8to8grab & #he second parameter is how many characters you want to grab. 2f you lea!e this out, () will grab all the characters to the end of your word. "ere s some code to try, with a new button1

3:

*e re using Substring with two parameters -B, ;.. &ut since we re grabbing to the end of the word, we could ha!e left out the , ; at the end. #o test it out, change the meFme.com to meFme.con. ?un your programme and you should see ,&ad 9mail Address,. (hange it back and the email address will be 0K.

Exer"ise M 6se Substring to check that an email address ends in .co.uk. +or the email address to check, use en$uiryFme.co.uk.

Split an 9oin in C# .NET


T!e Split Met!o
#he Split method is used to split a string of text and put the words into an array. +or example, you could grab a line of text from a text file. 9ach position in the array would then hold a word from the line of text. An example may clear things up. Add another button to your form. Double click the button to get at the code, and add the following1

3;

?un the programme and click your button. %ou should see each word from the line of text display. 2n the first line of the code, we re setting up a string with three items in it. 9ach item is separated by a comma. -(omma separated files from software like 9xcel are $uite common, and so too is parsing each line of text.. +or the second line, we ha!e this1 string:; wor -rra< = line()Text.Split% 4/4 &; #he first part sets up a string array that we !e called wordArray. After the e$uals sign, we ha!e this1 line()Text.Split% 4/4 &; #he !ariable called line0f#ext is ob!iously the line of text we want to examine. +or the round brackets of Split, we !e typed a comma surrounded by single $uotes. #hat s because () needs to know what character in your line of text you are using to separate the words. #his is known as the delimiter. 2f our line of text were this instead1 string line()Text = #item1 item2 item=#; we d use a blank space as a delimiter. Like this1 string:; wor -rra< = line()Text.Split% 4 4 &; #his time, we !e typed a blank space between the single $uotes. &ut () will split the line, and put each part into the array we !e set up. -2t won t include the delimiter.. +or our line of text we only ha!e three words. So the Message box in our code displays what is at position >, position 3, and position 7 in our array. 2f you don t know how many position there are in the array -if you ha!e lines of text that !ary in siHe, for example., the you can loop through each position1

3B

)orea"! %string s in wor -rra<& > MessageBox.S!ow% s &; ? #he Split method can take other parameters, and get a bit complex. So we ll lea!e it there in this beginners book5

T!e 9oin Met!o


%ou can 4oin the pieces of your arrays back together again. 8oin, howe!er, is not a method a!ailable to ordinary strings. 2nstead, you can access it through the String class. Like this1

2n the code abo!e, we !e used Split to split the line of text and put the words into an array. *e !e then used 8oin to create a single line of text again. #his time, though, the words are separated with hyphens and not commas. #o use 8oin, first type the word String -with a capital letter.. After a dot, you should then see the 8oin method appear on the 2ntelliSense list. 2n between the round brackets of 8oin, you first need the character your want to use as a delimiter. /ote that this is surrounded by double $uotes. 2f you use single $uotes, () will think it is the char !ariable type. &ut you need to use the string !ariable type, so you ll get an error. After a comma, you type the name of the array you want to 8oin together

3A

- C# .NET @angman Aame


#o put all our () string theory into practice, we !e de!eloped a simple wordEguessing game, popularly known as hangman in the 6K. #he pro4ect is amongst the download files for this course. Look for the folder called "angman. 2nside of this, you ll find a hangman.!bpro4. 0pen up this pro4ect in your () ./9# software. ?un the programme and you should see this1

After clicking the /ew *ord button, you click on letters of the alphabet. 2f the word contains the letter you clicked on, it appears in the word. 2f you guess incorrectly then you lose a life. #he game is o!er when you either guess the word, or run out of li!es. 0ur !ersion contains words of only three letters, so that you can see what s going on. #here are also message boxes, used to display the words. #his is for testing purposes. 0pen up the code for the pro4ect and you ll see that it is hea!ily commented. *e won t go through the code stepEbyEstep here, but examine the code and the comments for yourself. 'ay particular attention to these () string methods1 'n ex() 'nsert 1emo6e

3G

Substring ToUpper 2f you are unsure about any of them, go back a few pages and look at the explanation in this book. As you re going through the code, though, bear in mind that what the programme is trying to do is manipulate strings and characters, using as many inbuilt () methods as possible. #his is the kind of manipulation that you need to be able to do in your own programming. 0nce you !e got a good idea of how the programme works, try this exercise. Exer"ise #he game only uses words of three letters, at the moment. #here are ten words in all. Amend the code to use words of nine letters. %ou can, of course, use your own. &ut here s 3> nine letter words for you, if you re stuck. #hey are all countries1 -rgentina -ustralia Areenlan Auatemala 'n onesia $it!uania Ma"e onia Mauritius Ni"aragua VeneBuela +or this exercise, it s not 4ust a $uestion of changing the words in the array. (an you see what else you need to changeL

3@

Вам также может понравиться