VB.Net Tutorial/Data Type/String
Содержание
- 1 Catch Exception for String.Substring
- 2 Change tab to space
- 3 Check a Credit card number
- 4 Copy characters from string1 into character Array
- 5 Count Vowels
- 6 Declare String Variable and assign value
- 7 Demonstrating method GetHashCode of class String
- 8 Demonstrating String class constructors
- 9 Get string morse code
- 10 Insert method returns the resulting string
- 11 Insert sub string by index
- 12 Join string
- 13 Make a reference copy
- 14 Read String value from Keyboard
- 15 Reverse a string
- 16 String.Empty
- 17 String Length property
- 18 String operation timing
- 19 SubString
- 20 ToString
Catch Exception for String.Substring
<source lang="vbnet">public class Test
public Shared Sub Main Dim strCaption As String strCaption = "Answer" Try Console.WriteLine(strCaption.Substring(10, 1)) Catch ex As Exception Console.WriteLine(ex.Message) End Try
End Sub
End class</source>
startIndex cannot be larger than length of string. Parameter name: startIndex
Change tab to space
<source lang="vbnet">Public Class Tester
Public Shared Sub Main Dim tabs As String = "This~is~~a~tabbed~~~string".Replace("~"c, vbTab) Dim spaces As String = TabsToSpaces(tabs, 8) Dim periods As String = spaces.Replace(" "c, "."c) Console.WriteLine(tabs) Console.WriteLine(spaces) Console.WriteLine(periods) End Sub Public Shared Function TabsToSpaces(ByVal source As String, ByVal tabSize As Integer) As String Dim result As New System.Text.StringBuilder Dim counter As Integer For counter = 0 To source.Length - 1 If (source.Chars(counter) = vbTab) Then Do result.Append(Space(1)) Loop Until ((result.Length Mod tabSize) = 0) Else result.Append(source.Chars(counter)) End If Next counter Return result.ToString() End Function
End Class</source>
This is a tabbed string This is a tabbed string This....is..............a.......tabbed..................string
Check a Credit card number
<source lang="vbnet">" Quote from "Visual Basic 2005 Cookbook Solutions for VB 2005 Programmers "by Tim Patrick (Author), John Craig (Author) "# Publisher: O"Reilly Media, Inc. (September 21, 2006) "# Language: English "# ISBN-10: 0596101775 "# ISBN-13: 978-0596101770
Public Class Tester
Public Shared Sub Main
Console.WriteLine(VerifyCreditCard("123123123123123123"))
End Sub Private Shared Function VerifyCreditCard(ByVal cardNumber As String) As Boolean " ----- Given a card number, make sure it is valid. This method " uses the Luhn algorithm to verify the number. This routine " assumes that cardNumber contains only digits. Dim counter As Integer Dim digitTotal As Integer Dim holdValue As Integer Dim checkDigit As Integer Dim calcDigit As Integer Dim useCard As String " ----- Perform some initial checks. useCard = Trim(cardNumber) If (IsNumeric(useCard) = False) Then Return False " ----- Separate out the last digit, the check digit. For cards with " an odd number of digits, prepend with a zero. If ((Len(useCard) Mod 2) <> 0) Then useCard = "0" & useCard checkDigit = useCard.Substring(Len(useCard) - 1, 1) useCard = useCard.Substring(0, Len(useCard) - 1) " ----- Process each digit. digitTotal = 0 For counter = 1 To Len(useCard) If ((counter Mod 2) = 1) Then " ----- This is an odd digit position. Double the number. holdValue = CInt(Mid(useCard, counter, 1)) * 2 If (holdValue > 9) Then " ----- Break the digits (e.g., 19 becomes 1+9). digitTotal += (holdValue \ 10) + (holdValue - 10) Else digitTotal += holdValue End If Else " ----- This is an even digit position. Simply add it. digitTotal += CInt(Mid(useCard, counter, 1)) End If Next counter " ----- Calculate the 10"s complement of both values. calcDigit = 10 - (digitTotal Mod 10) If (calcDigit = 10) Then calcDigit = 0 If (checkDigit = calcDigit) Then Return True Else Return False End Function
End Class</source>
False
Copy characters from string1 into character Array
<source lang="vbnet">Module Tester
Sub Main() Dim string1 As String Dim characterArray As Char() Dim i As Integer Dim quotes As Char = ChrW(34) string1 = "hello there" characterArray = New Char(5) {} string1.CopyTo(0, characterArray, 0, 5) For i = 0 To characterArray.GetUpperBound(0) Console.WriteLine(characterArray(i)) Next End Sub " Main
End Module</source>
h e l l o
Count Vowels
<source lang="vbnet">Imports System.IO public class Test
public Shared Sub Main Console.WriteLine("VOWELS COUNTED: " & CountTheVowels("asdffdsaasdf")) End Sub Private Shared Function CountTheVowels(ByVal strSomeString As String) As Integer Dim intCount As Integer = 1 Dim intTotal As Integer = 0 Dim intPosition As Integer "Loop through the string and count the vowels. Do While intCount <= strSomeString.Length intPosition = InStr("aeio", strSomeString.Substring(intCount, 1).ToLower) If intPosition > 0 Then intTotal += 1 End If Loop Return intTotal End Function
End class</source>
Declare String Variable and assign value
<source lang="vbnet">Module Module1
Sub Main() Dim EmployeeName As String Dim EmployeePhoneNumber As String Dim EmployeeSalary As Double Dim NumberOfEmployees As Integer EmployeeName = "James Bond" EmployeePhoneNumber = "555-1212" EmployeeSalary = 45.0 NumberOfEmployees = 1 Console.WriteLine("Number of employees: " & NumberOfEmployees) Console.WriteLine("Employee name: " & EmployeeName) Console.WriteLine("Employee phone number: " & EmployeePhoneNumber) Console.WriteLine("Employee salary: " & EmployeeSalary) End Sub
End Module</source>
Number of employees: 1 Employee name: James Bond Employee phone number: 555-1212 Employee salary: 45
Demonstrating method GetHashCode of class String
<source lang="vbnet">Module Tester
Sub Main() Dim string1 As String = "hello" Dim string2 As String = "Hello" Console.WriteLine(string1.GetHashCode() ) Console.WriteLine(string2.GetHashCode()) End Sub " Main
End Module</source>
-695839 -694847
Demonstrating String class constructors
<source lang="vbnet">Module Tester
Sub Main() Dim characterArray As Char() Dim quotes As Char = ChrW(34) Dim originalString, string1, string2, string3, string4 As String characterArray = New Char() {"A"c, "B"c, "C"c, "D"c, "E"c, "F"c, " "c, "G"c, "H"c} originalString = "test" string1 = originalString string2 = New String(characterArray) string3 = New String(characterArray, 6, 3) string4 = New String("C"c, 5) Console.WriteLine(string1) Console.WriteLine("string2 = " & string2 ) Console.WriteLine("string3 = " & string3 ) Console.WriteLine("string4 = " & string4 ) End Sub " Main
End Module</source>
test string2 = ABCDEF GH string3 = GH string4 = CCCCC
Get string morse code
<source lang="vbnet">Public Class Tester
Public Shared Sub Main Dim source As String = "Hello world!" Dim characters As String = _ "~ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,:?"-/""" Dim morse() As String = { _ "?", ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", _ "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", _ "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", _ "-.--", "--..", "-----", ".----", "..---", "...--", _ "....-", ".....", "-....", "--...", "---..", "----.", _ ".-.-.-", "--..--", "---...", "..--..", ".----.", _ "-....-", "-..-.", ".-..-."} Dim counter As Integer Dim position As Integer For counter = 0 To source.Length - 1 position = characters.IndexOf(Char.ToUpper( _ source.Chars(counter))) If (position < 0) Then position = 0 Console.Write (source.Substring(counter, 1) & " ") Console.WriteLine(morse(position)) Next counter End Sub
End Class</source>
H .... e . l .-.. l .-.. o --- ? w .-- o --- r .-. l .-.. d -.. ! ?
Insert method returns the resulting string
<source lang="vbnet">public class Test
public Shared Sub Main Dim s1 As New String("Greeting") s1.Insert(4, "sdss") "DOES NOT CHANGE S1!!!! s1 = s1.Insert(8, "s") "changes Greeting to Greetings Console.WriteLine(s1.Length) Console.WriteLine(s1) End Sub
End class</source>
9 Greetings
Insert sub string by index
<source lang="vbnet">Option Strict On
Imports System Class Tester Public Shared Sub Main( ) Dim s1 As String = "abcd" Dim s2 As String = "ABCD" Dim s3 As String = "AAAAs " s3 = s3 & "development" Dim s5 As String = String.Copy(s2) " Console.WriteLine("s5 copied from s2: {0}", s5) Console.WriteLine("String s3 is {0} characters long. ",s5.Length) Console.WriteLine("s3: {0}", s3) " hold the location of provides as an integer Dim location As Integer = s3.IndexOf("a") Dim s10 As String = s3.Insert(location, "u") Console.WriteLine("s10: {0}", s10) End Sub "Main End Class "Tester</source>
s5 copied from s2: ABCD String s3 is 4 characters long. s3: AAAAs development Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negativ e and less than the size of the collection. Parameter name: startIndex at System.String.Insert(Int32 startIndex, String value) at Tester.Main()
Join string
<source lang="vbnet">Imports System.Collections public class Test
public Shared Sub Main Dim s() As String = {"one", "two", "three"} "a string array Dim s2 As String s2 = s2.Join(", ", s) Console.WriteLine(s2) End Sub
End class</source>
one, two, three
Make a reference copy
<source lang="vbnet">Public Class Tester
Public Shared Sub Main Dim arrayA() As String = {"One", "Two", "Three", "Four", "Five", "Six"} Console.WriteLine(Join(arrayA, ",")) Dim arrayB() As String = {"A", "B", "C", "D", "E", "E", "F", "G", "H"} Console.WriteLine(Join(arrayB, ",")) " ----- Make a reference copy. Dim arrayC() As String = arrayA Console.WriteLine(Join(arrayC, ",")) End Sub
End Class</source>
One,Two,Three,Four,Five,Six A,B,C,D,E,E,F,G,H One,Two,Three,Four,Five,Six
Read String value from Keyboard
<source lang="vbnet">Module Module1
Sub Main() Dim FirstName As String Console.Write("Name: ") FirstName = Console.ReadLine() Console.WriteLine(FirstName) End Sub
End Module</source>
Name: name name
Reverse a string
<source lang="vbnet">public class Test
public Shared Sub Main Dim objTS As TimeSpan Dim dteStart As Date Dim strText As String Dim strChar As String Dim intChar As Integer dteStart = Now() strText = "12345678" Dim intLen As Integer = Len(strText) For intChar = 1 To CInt(intLen / 2) strChar = Mid(strText, intChar, 1) Mid(strText, intChar, 1) = Mid(strText, intLen - intChar - 1, 1) Mid(strText, intLen - intChar - 1) = strChar Next objTS = Now().Subtract(dteStart) Console.WriteLine(objTS.ToString) Console.WriteLine(strText) End Sub
End class</source>
00:00:00 65342178
String.Empty
<source lang="vbnet">Option Strict On Public Module modMain
Public Sub Main() Console.WriteLine(String.Empty) End Sub
End Module</source>
String Length property
<source lang="vbnet">Module Tester
Sub Main() Dim string1 As String Dim characterArray As Char() Dim i As Integer Dim quotes As Char = ChrW(34) string1 = "hello there" characterArray = New Char(5) {} Console.WriteLine("Length of string1: " & string1.Length) End Sub " Main
End Module</source>
Length of string1: 11
String operation timing
<source lang="vbnet">Public Class Tester
Public Shared Sub Main Dim content As String = "" Dim result As New System.Text.StringBuilder Dim counter As Integer Dim dateTime1 As Date Dim dateTime2 As Date Dim dateTime3 As Date Dim loopCount As Integer = 15000 dateTime1 = Now For counter = 1 To loopCount content &= counter.ToString() Next counter dateTime2 = Now For counter = 1 To loopCount result.Append(counter.ToString()) Next counter dateTime3 = Now content = String.Format( _ "First loop took {0:G4} ms, the second took {1:G4} ms.", _ dateTime2.Subtract(dateTime1).TotalMilliseconds, _ dateTime3.Subtract(dateTime2).TotalMilliseconds) Console.WriteLine(content) End Sub
End Class</source>
First loop took 1734 ms, the second took 0 ms.
SubString
<source lang="vbnet">Option Strict On
Imports System Class Tester Public Shared Sub Main( ) Dim s1 As String = "One Two Three Four" Dim index As Integer index = s1.LastIndexOf(" ") Dim s2 As String = s1.Substring((index + 1)) s1 = s1.Substring(0, index) index = s1.LastIndexOf(" ") Dim s3 As String = s1.Substring((index + 1)) s1 = s1.Substring(0, index) index = s1.LastIndexOf(" ") Dim s4 As String = s1.Substring((index + 1)) s1 = s1.Substring(0, index) index = s1.LastIndexOf(" ") Dim s5 As String = s1.Substring((index + 1)) Console.WriteLine("s1: {0}", s1) Console.WriteLine("s2: {0}", s2) Console.WriteLine("s3: {0}", s3) Console.WriteLine("s4: {0}", s4) Console.WriteLine("s5: {0}", s5) End Sub "Main End Class "Tester</source>
s1: One s2: Four s3: Three s4: Two s5: One
ToString
<source lang="vbnet">Public Class Tester
Public Shared Sub Main Dim someInt As Integer = 123 Dim someDouble As Double = Math.PI Dim someString As String = "Testing" Dim someDate As Date = #7/4/1776 9:10:11 AM# Dim someDecimal As Decimal = 1D / 3D Dim result As New System.Text.StringBuilder result.Append("someInt.ToString ") result.AppendLine(someInt.ToString()) result.Append("someDouble.ToString ") result.AppendLine(someDouble.ToString()) result.Append("someString.ToString ") result.AppendLine(someString.ToString()) result.Append("someDate.ToString ") result.AppendLine(someDate.ToString()) result.Append("someDecimal.ToString ") result.Append(someDecimal.ToString()) Console.WriteLine(result.ToString())
End Sub
End Class</source>
someInt.ToString 123 someDouble.ToString 3.14159265358979 someString.ToString Testing someDate.ToString 04/07/1776 9:10:11 AM someDecimal.ToString 0.3333333333333333333333333333