String Manipulation

32
String Manipulation Students should fill out String Worksheet along with this. Students can use worksheet on test.

description

String Manipulation. Students should fill out String Worksheet along with this. Students can use worksheet on test. Overview. String manipulation, like most programming tools, are easy to understand but difficult to know how to use. - PowerPoint PPT Presentation

Transcript of String Manipulation

String Manipulation

String ManipulationStudents should fill out String Worksheet along with this. Students can use worksheet on test.OverviewString manipulation, like most programming tools, are easy to understand but difficult to know how to use.Most string functions are never used just by themselves. Typically they are used in combination with other string functions, loops, if statements etc

The following slides are only a few of the string functions available.

OverviewStrings are really just a bunch of characters all put together. It is important to understand that the first character is the ZERO character.When counting characters it would like:

GREENH0123456Toupper and tolowerLengthSimply returns how many characters exist in a string.Syntax: string.lengthExamples: Dim x As String = "Green H" MessageBox.Show(x.Length) Displays 7

MessageBox.Show("Help".Length) Displays 4

Dim x As String = "Green H" For i = 0 To x.Length run a loop dependent on lengthstatement(s) Next i

TrimRemoves all leading and trailing white-space characters from a string. (For us white-space will mean spaces, but it includes tab, linefeed, carriage-return, formfeed, vertical-tab, and newline characters )Syntax: string.Trim[(char,,char)]It only does it at the start and end of the string.ExamplesDim x As String = " Green H "MessageBox.Show(x.Length) Displays 13x = x.TrimMessageBox.Show(x.Length) Displays 7

Trim continuedYou can specify what characters you want to remove.

Dim x As String = " TEricaE% "x = x.Trim("E"c, "%"c) remove leading &trailing E and %MessageBox.Show(x) Displays TErica spaces are left

Dim x As String = " TEricaE%B "x = x.Trim("E"c, "%"c) remove leading &trailing E and %MessageBox.Show(x) Displays TEricaE%B spaces are left

What is the c? The c is what is know as a literal constant and it simply tells the computer to look at E as a character instead of a string.7TrimStartThe exact same as TRIM but it only works at the start of the string.TrimEndThe exact same as TRIM but it only works at the end of the string.

RemoveUsed to remove any character from anywhere in a string.Syntax: string.Remove(startIndex, count)Examples: Dim x As String = "Hey Herotp" x = x.Remove(8, 2) x is now Hey Hero x = "Hey Herotp" x = x.Remove(5) x is now Hey H

HEYHEROTP0123456789This is a start base 0 function. 10ReplaceReplaces all occurrences of a sequence of characters in a string with another sequence of characters.Syntax: string.replace(oldvalue,newvalue)Examples:Dim x As String = "The dog do Do"x = x.Replace("d", "H") x = The Hog Ho Do

Dim x As String = "The dog do do"x = x.Replace("do", "ccc") x = The cccg ccc ccc

Notice the case sensitive nature of the replace function.11Mid Statement (Used to replace part of string)Replaces a specific number of characters in a string with characters from another string.Syntax:Mid(targetString, start [,count]) = replacementStringMid Statement continuedExamples:Dim TestString As String = "The dog jumps"Mid(TestString, 5, 3) = "fox" 'Returns "The fox jumps".Mid(TestString, 5) = "cow" 'Returns "The cow jumps".Mid(TestString, 5) = "cow jumped over" 'Returns "The cow jumpe".Mid(TestString, 5, 3) = "duck" 'Returns "The duc jumpe".Mid(TestString, 5, 1) = game" 'Returns "The guc jumpe".

This actually replaces the TestString variable with the updated stuff.The last line is unique because it wants to replace just 3 letters but the word has 4 letters, so it only replaces 3.13padleftAdds characters to the start of a string until a string is a specified length.This is used with database work and fixed record sizes.Syntax: string.padleft(length[, character])If character parameter is missing a space is defaultExamples:Dim x As String = "687 6985"x = x.PadLeft(10, "*"c) x = **687 6985

padrightAdds characters to the end of a string until a string is a specified length.Syntax: string.padright(length[, character])If character parameter is missing a space is defaultExamples:Dim x As String = "687 6985"x = x.PadRight(10, "*"c) x = 687 6985**

insertInserts characters within a string. (One based)Syntax: string.insert(startindex,value)Examples:Dim ssn As String = 987654321ssn = ssn.Insert(3, "-") You get 987-654321ssn = ssn.Insert(6, "-") You get 987-65-4321Searching StringsThe next four methods deal specifically with searching strings.These search methods are mainly used for conditional checks in IF and LOOP statements, or they return a numerical value stating what place a character is at in a string.

startswithDetermines whether a specific sequence of characters occurs at the beginning of a string. Returns a Boolean value. It is case sensitive. Syntax: string.startswith(substring)Examples: Dim x As String = "Green High School" If x.StartsWith("Green") Then MessageBox.Show("We found Green") End If

endswithDetermines whether a specific sequence of characters occurs at the end of a string. Returns a Boolean value. It is case sensitive. Syntax: string.endswith(substring)Examples: Dim x As String = "Green High School" If x.endsWith("Green") Then MessageBox.Show("Ends with Green") Else MessageBox.Show("Does not end with Green") End If

containsUsed to determine whether a substring exists anywhere within a string. Returns a Boolean. It is case sensitive.Syntax: string.contains(substring)Examples: Dim x As String = "I go to Green High School" If x.Contains("Green") Then MessageBox.Show("Green found") End If

indexofSearches a string for a substring and if it is found it returns an integer value that represents the location of the substring being searched for. If it is not found then a -1 value is returned. (Zero Based)Syntax: string.IndexOf(substring[, startIndex])Examples: Dim x As String = "I go to Green High School" Dim y As Int16 y = x.IndexOf("Green") Returns 8 y = x.IndexOf("Green",9) Returns -1 y = x.IndexOf("o") Returns 3y = x.IndexOf("High", 9) Returns 14

Substring This method will let you pull out a substring contained in a string.Syntax: string.SubString(startIndex[,count])Examples:Dim fullname As String = "Barack Obama"Dim firstname, lastname As String

firstname = fullname.Substring(0, 6) 'Returns Baracklastname = fullname.Substring(6) 'Returns ObamaMessageBox.Show(fullname.Substring(2, 4)) 'Displays rackString.compareSimply compares two strings and returns an Integer. The optional ignoreCase parameter is by default false.Three values are returned0 means the strings are equal1 means string 1 is > string 2 (string 2 would come first alphabetically)-1 means string 1 is < string 2 (string 1 would come first alphabetically)This method uses Word Sort Rules which states that numbers are less than lowercase letters and lowercase is less than uppercase.Syntax: string.compare(string1, string2[,ignoreCase])Examples:

String.Compare Examples String.Compare("ERIC", "eric") 'returns 1String.Compare("eric", "ERIC") 'returns -1String.Compare("ERIC", "ERIC") 'returns 0String.Compare("eric", "ERIC", True) 'returns 0String.Compare(Bob", Eric") 'returns -1String.Compare(E", e") 'returns 1String.Compare(3", e") 'returns -1

likeCompares two strings but the comparison is based on patterns and you create the patterns. Examples:You want every string that starts with the word NewYou want every string with 3 numbers at front of string.You want every string that contains a a range of characters.A Boolean value is returned.

Syntax: string like patternPatterns can involve cryptic things like *, ?, #, [list]. The following slides explain the pattern possibilities. This is a powerful tool.

Like Examples using * patternThe * is for zero or more characters.

If state Like "M*" Then MessageBox.Show("The states first letter is M")End If

If state Like *o" Then MessageBox.Show("The states last letter is o")End If

If state Like *nn*" Then MessageBox.Show("The state contains the letter s nn somewhere in the middle of name)End ifLike Examples using ? patternThe ? is for any single character.

"BAT123khg" Like "B?T This returns false.BT" Like "B?T This returns false.byT" Like "B?T This returns false.ByT" Like "B?T This returns true.B8T" Like "B?T This returns true.

Like Examples using # patternUsed to compare against any single digit 0-9

"hi5" Like "hi#" Returns true."hi5" Like "hithere*" Returns false."4allh8ters" Like "#allh#ters" Returns true."(330) 699-8765" Like "(###) ###-####" Returns true."(33) 699-8765" Like "(###) ###-####" Returns false.

Like Examples with ?, #, *You tell me true or false"CABT123khg" Like "C*T#khg""CABT3khg" Like "C*T#k*""CAT3khg" Like "C??T3*g""CAT3khg" Like "C?T3*g"FalseTrueFalseTrueLike Examples using [charList]For i = 0 To wordstr.Length - 1 If wordstr.Substring(i, 1) Like "[0-9]" Then MessageBox.Show("No numbers are allowed") End IfNext

wordstr.Substring(i, 1) Like "[!0-9]wordstr.Substring(i, 1) Like "[a-zA-Z]wordstr.Substring(i, 1) Like B[AEIOU]T"Create a program that allows a user to enter a password that contains 5,6 or 7 characters. The application will display a new password using three rules.Replace all vowels with the letter X.Replace all numbers with the letter Z.Reverse the characters in the password. Dim x As String = mytext.Text.ToUpper Dim y As String = String.Empty

If x.Length.ToString Like "[5-7]" Then For i = 0 To x.Length - 1 If x.Substring(i, 1) Like "[AEIOU]" Then Mid(x, i + 1, 1) = "X" ElseIf x.Substring(i, 1) Like "[0-9]" Then Mid(x, i + 1, 1) = "Z" End If Next

For i = 0 To x.Length - 1 y = x.Substring(i, 1) + y Next MessageBox.Show(y) Else MessageBox.Show("Password must be 5, 6 or 7 characters.") End If31Phone Number Problem Everyone types in phone numbers differently. Examples are 330 655 1234 or (330) 655-1234 or 330.699.1234 or 3306551234 or 330-655-1234 etc... However people type a number is up to them but as a computer this cause problems. A computer only likes phone numbers in one method. You are to write code that will accept a phone number to be typed in in any method but will format it to look like 330.456.1234 format. Once a user types in the number and clicks Okay then a properly formatted phone number will appear in the same box the bad formatted number came from.How do you do thisGet number and extract all characters that aren't numbers. Ensure that 10 digits are entered, otherwise have user do it again with a popup. Put a period in after the third and sixth number.

Dim x As String = mytext.Text Dim y As String = String.Empty

For i = 0 To x.Length - 1 If x.Substring(i, 1) Like "[0-9]" Then y += x.Substring(i, 1) Next

If y.Length = 10 Then y = y.Insert(3, ".") y = y.Insert(7, ".") mytext.Text = y Else mytext.Text = "Invalid Input" End If32