2.1.1.Hexadecimal Byte, UInteger and Integer
|
Option Strict On
Public Module modMain Public Sub Main() Dim maxValue As Byte = &HFF Dim posValue As UInteger = &HF034 Dim negValue As Integer = &HF034 Console.WriteLine(maxValue) Console.WriteLine(posValue) Console.WriteLine(negValue) End Sub End Module
|
2.1.2.Integer Family MaxValue
|
Public Class Tester Public Shared Sub Main Dim result As New System.Text.StringBuilder() result.AppendLine("MaxValue...")
Dim maxByte As Byte = Byte.MaxValue Dim maxSByte As SByte = SByte.MaxValue Dim maxShort As Short = Short.MaxValue Dim maxUShort As UShort = UShort.MaxValue Dim maxInteger As Integer = Integer.MaxValue Dim maxUInteger As UInteger = UInteger.MaxValue Dim maxLong As Long = Long.MaxValue Dim maxULong As ULong = ULong.MaxValue
result.Append("Byte ").AppendLine(maxByte) result.Append("SByte ").AppendLine(maxSByte) result.Append("Short ").AppendLine(maxShort) result.Append("UShort = ").AppendLine(maxUShort) result.Append("Integer = ").AppendLine(maxInteger) result.Append("UInteger = ").AppendLine(maxUInteger) result.Append("Long = ").AppendLine(maxLong) result.Append("ULong = ").AppendLine(maxULong)
Console.WriteLine(result.ToString()) End Sub End Class
|
Long = 9223372036854775807
ULong = 18446744073709551615
2.2.1.Define Integer variable and assign value
|
Module Module1 Sub Main( ) Dim myInt As Integer = 7 Console.WriteLine("Initialized myInt: {0}", myInt) myInt = 5 Console.WriteLine("After assignment myInt: {0}", myInt) End Sub End Module
|
After assignment myInt: 5
2.2.2.Add two integers together
|
Module Tester
Sub Main() Dim firstNumber, secondNumber As String
Dim number1, number2, sumOfNumbers As Integer
firstNumber = 10
secondNumber = 20
number1 = firstNumber number2 = secondNumber
sumOfNumbers = number1 + number2 ' add numbers Console.WriteLine("The sum is {0}", sumOfNumbers)
End Sub ' Main
End Module
|
2.2.3.Integer calculation
|
public class Test public Shared Sub Main Dim n As Integer
' try adding numbers... n = 16 n += 10.23 Console.WriteLine("Addition " & n)
' try subtracting numbers... n = 24 n -= 2 Console.WriteLine("Subtraction " & n)
' try multiplying numbers... n = 6 n *= 10 Console.WriteLine("Multiplication " & n)
' try dividing numbers... n = 12 n /= 6 Console.WriteLine("Division " & n)
End Sub End class
|
2.2.4.Swap two integers without using a third
|
Imports System.Drawing Imports System.Drawing.Drawing2D Imports System.Collections Public Class Tester Public Shared Sub Main Dim firstValue As Integer Dim secondValue As Integer
firstValue = 17 secondValue = 123 Console.WriteLine("Before swap: {0}, {1}",firstValue, secondValue)
firstValue = firstValue Xor secondValue secondValue = firstValue Xor secondValue firstValue = firstValue Xor secondValue Console.WriteLine("After swap: {0}, {1}",firstValue, secondValue) End Sub End Class
|
2.2.5.MinValue and MaxValue of Integer
|
public class Test public Shared Sub Main Dim iNum As Integer Console.WriteLine("Integer: " & iNum.MinValue & " to " & iNum.MaxValue) End Sub End class
|
Integer: -2147483648 to 2147483647
|
public class Test public Shared Sub Main Try Dim num_items As Integer = Integer.Parse("123") Catch ex As Exception Console.WriteLine(ex.Message) End Try End Sub End class
|
|
Module Module1
Const x As String = "This is a string"
Sub Main() Dim a As Double = 5.678 Dim b As Int32 = 123
Console.WriteLine(a.ToString) Console.WriteLine(b.ToString) Console.WriteLine(456.987.ToString)
Dim c As Integer Console.WriteLine(c.GetType()) Console.WriteLine(c.GetType().ToString)
End Sub
End Module
|
2.2.8.Integer boolean calculation: Or, And, Xor, Not
|
public class Test public Shared Sub Main Dim I As Integer I = 3 Or 4 Console.WriteLine(I) I = 2 And 4 Console.WriteLine(I) I = 3 Xor 3 Console.WriteLine(I) I = Not 5 Console.WriteLine(I) End Sub End class
|
2.2.9.Parse Integer variable and get hash code from Integer
|
public class Test public Shared Sub Main Dim Number As String Number = "4" Console.WriteLine(Integer.Parse(Number)) Console.WriteLine(Number.GetHashCode())
End Sub End class
|
2.2.10.Use Integer.CompareTo to compare two integers
|
public class Test public Shared Sub Main Dim I As Integer = 0 Dim S As Integer = 8 Console.WriteLine(I.CompareTo(S))
End Sub End class
|
2.2.11.Integer format: D10
|
Public Class Tester Public Shared Sub Main Dim intNumber As Integer = 12345 Console.WriteLine(intNumber.ToString("D10"))
End Sub End Class
|
2.2.12.Pass Integer to a function by reference
|
Module Module1
Sub ParameterChange(ByRef A As Integer) A = 1001 Console.WriteLine("Value of A in subroutine " & A) End Sub
Sub Main() Dim Number As Integer = 100
Console.WriteLine("Number before function call: " & Number) ParameterChange(Number) Console.WriteLine("Number before function call: " & Number) End Sub
End Module
|
Number before function call: 100
Value of A in subroutine 1001
Number before function call: 1001
2.2.13.Pass Integer to a function by value
|
Module Module1
Sub NoChangeToParameter(ByVal A As Integer) A = 1001 Console.WriteLine("Value of A in subroutine " & A) End Sub
Sub Main() Dim Number As Integer = 100
Console.WriteLine("Number before function call: " & Number) NoChangeToParameter(Number) Console.WriteLine("Number before function call: " & Number) End Sub
End Module
|
Number before function call: 100
Value of A in subroutine 1001
Number before function call: 100
2.2.14.Compare Integer value in If statement
|
Module Module1
Sub Main() Dim TestScore As Integer = 80
If TestScore >= 90 Then Console.WriteLine("Test grade: A") ElseIf TestScore >= 80 Then Console.WriteLine("Test grade: B") ElseIf TestScore >= 70 Then Console.WriteLine("Test grade: C") Else Console.WriteLine("Test grade: F") End If
End Sub
End Module
|
2.2.15.Integer OverflowException
|
Public Class Tester Public Shared Sub Main Dim A, B As Integer Dim C As Integer Try A = 9999 B = 9999 C = A * B * B * B Catch Except As OverflowException Console.WriteLine("Overflow error detected") End Try End Sub
End Class
|
2.2.16.Implicit conversion of an integer to a string
|
Module Tester Public Sub Main() Dim iInteger As Integer = 5280 Dim lLong As Long Dim bytByte As Byte Dim sngSingle As Single Dim dblDouble As Double Dim decDecimal As Decimal
Console.WriteLine("Implicit conversion of an integer to a string: {0}", iInteger) End Sub
End Module
|
Implicit conversion of an integer to a string: 5280
2.2.17.Explicit conversion of an integer to a string
|
Module Tester Public Sub Main() Dim iInteger As Integer = 5280 Dim lLong As Long Dim bytByte As Byte Dim sngSingle As Single Dim dblDouble As Double Dim decDecimal As Decimal
Console.WriteLine("Explicit conversion of an integer to a string: {0}", CStr(iInteger)) End Sub
End Module
|
Explicit conversion of an integer to a string: 5280
2.3.1.Convert the part of a Byte array to a String with the ToString method.
|
' Example of some BitConverter.ToString( ) method overloads. Imports System Imports Microsoft.VisualBasic
Module BytesToStringDemo Sub Main( ) Dim arrayOne as Byte( ) = { _ 0, 0, 0, 0, 128, 63, 0, 0, 112, 65, _ 0, 255, 127, 71, 0, 0, 128, 59, 0, 0, _ 0, 0, 0, 192, 255, 0, 0, 128, 255, 0, _ 0, 128, 127 }
Console.WriteLine(BitConverter.ToString( arrayOne)) End Sub End Module
|
2.4.1.Display negative SByte value using the standard numeric format specifiers and a number of specific CultureInfo objects.
|
Imports System.Globalization
Module Example Public Sub Main() Dim cultures() As CultureInfo = {CultureInfo.CreateSpecificCulture("en-US"), _ CultureInfo.CreateSpecificCulture("fr-FR"), _ CultureInfo.CreateSpecificCulture("es-ES") } Dim negativeNumber As SByte = -45 Dim specifiers() As String = {"E2", "F", "N", "P", "X2"}
For Each specifier As String In specifiers For Each culture As CultureInfo In Cultures Console.WriteLine("{0,2} format using {1} culture: {2, 16} {3, 16}", _ specifier, culture.Name, _ negativeNumber.ToString(specifier, culture))
Next Next End Sub End Module
|
|
Module Module1
Sub Main() Dim Value As Short = 32767 Value = Value + 1 End Sub
End Module
|
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.
2.5.2.MinValue and MaxValue of Short
|
public class Test public Shared Sub Main Dim sNum As Short
Console.WriteLine("Short: " & sNum.MinValue & " to " & sNum.MaxValue)
End Sub End class
|
|
public class Test
public Shared Sub Main Dim flags As ULong flags = 100 ' Decimal 100.
Console.WriteLine(flags) ' Decimal. End Sub
End class
|
|
public class Test
public Shared Sub Main Dim flags As ULong flags = &H64 ' Hexadecimal &H64 = 6 * 16 + 4 = 96 + 4 = 100.
Console.WriteLine(Hex(flags)) ' Hexadecimal. End Sub
End class
|
|
public class Test
public Shared Sub Main Dim flags As ULong flags = &O144 ' Octal &O144 = 1 * 8 * 8 + 4 * 8 + 4 = 64 + 32 + 4 = 100.
Console.WriteLine(Oct(flags)) ' Octal. End Sub
End class
|
|
public class Test
Public Const MASK_READ As Long = &H1000& public Shared Sub Main End Sub End class
|
|
public class Test
Public Const MASK_READ_WRITE As Long = 1 Or 2 public Shared Sub Main Console.WriteLine(MASK_READ_WRITE) End Sub End class
|
2.7.3.MinValue and MaxValue of Long
|
public class Test public Shared Sub Main Dim lNum As Long Console.WriteLine("Long: " & lNum.MinValue & " to " & lNum.MaxValue) End Sub End class
|
Long: -9223372036854775808 to 9223372036854775807
|
Public Class Tester Public Shared Sub Main Dim ushortParse As UShort = UShort.Parse("65533")
Console.WriteLine(ushortParse) End Sub
End Class
|
2.8.2.Display a 16-bit unsigned integer value by using each standard format string and some custom format strings.
|
Imports System.Globalization
Module Example Public Sub Main() Dim value As UShort = 9 Dim specifiers() As String = { "G", "C", "D3", "E2", "e3", "F", _ "N", "P", "X", "000000.0", "#.0", _ "00000000;(0);**Zero**" }
For Each specifier As String In specifiers Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)) Next End Sub End Module
|
2.9.1.Declare Double type variable and assign value
|
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
|
Employee name: James Bond
Employee phone number: 555-1212
2.9.2.Define double and output its value
|
public class Test public Shared Sub Main Dim I As Integer = 2 I *= 5 Console.WriteLine(I) Dim D As Double = I / 3 Console.WriteLine(D)
End Sub End class
|
VB.Net Tutorial » Data Type » Double
|
|
|
2.9.3.Get Epsilon from Double
|
public class Test public Shared Sub Main Dim D As Double D = 5 Console.WriteLine(D.Epsilon)
End Sub End class
|
|
|
2.9.4.Show difference precision of Single and Double (1)
|
Module Module1
Sub Main() Dim A As Single = 0.123456789012345 Dim B As Double = 0.123456789012345
Console.WriteLine("Single: " & A) Console.WriteLine("Double: " & B)
End Sub
End Module
|
Double: 0.123456789012345
2.9.5.Single Double MaxValue and Memory Size (1)
|
Public Class Tester Public Shared Sub Main
Dim result As New System.Text.StringBuilder Dim maxSingle As Single = Single.MaxValue Dim maxDouble As Double = Double.MaxValue Dim sizeOfSingle As Integer = Runtime.InteropServices.Marshal.SizeOf(maxSingle.GetType) Dim sizeOfDouble As Integer = Runtime.InteropServices.Marshal.SizeOf(maxDouble.GetType)
result.Append("Memory size of a Single (bytes): ") result.AppendLine(sizeOfSingle) result.Append("Maximum value of a Single: ") result.AppendLine(maxSingle) result.AppendLine()
result.Append("Memory size of a Double (bytes): ") result.AppendLine(sizeOfDouble) result.Append("Maximum value of a Double: ") result.AppendLine(maxDouble)
Console.WriteLine(result.ToString()) End Sub
End Class
|
Memory size of a Single (bytes): 4
Maximum value of a Single: 3.402823E+38
Memory size of a Double (bytes): 8
Maximum value of a Double: 1.79769313486232E+308
|
Public Class Tester Public Shared Sub Main Dim doubleParse As Double = Double.Parse("3.1416")
Console.WriteLine(doubleParse) End Sub
End Class
|
2.9.7.Define and loop through double value array
|
Module Tester
Sub Main() Dim Values() As Integer = {100, 200, 300, 400, 500} Dim MyValues(5) As Integer Dim Prices() As Double = {25.5, 4.95, 33.4}
Dim I As Integer
For I = 0 To 4 Console.Write(Values(I) & " ") Next Console.WriteLine()
For I = 0 To Prices.GetUpperBound(0) Console.Write(Prices(I) & " ") Next End Sub
End Module
|
2.9.8.Read Double value from Keyboard
|
Module Module1
Sub Main() Dim Salary As Double Console.Write("Salary: ") Salary = Console.ReadLine() Console.WriteLine(Salary)
End Sub
End Module
|
2.9.9.Convert Double to Integer
|
Module Module1
Sub Main() Dim dblValue As Double Dim intValue As Integer dblValue = 1.2345678 intValue = dblValue Console.WriteLine(intValue) End Sub
End Module
|
|
Imports System
Module MyModule
Sub Main() Dim num As Double = Double.Parse("12.12")
Dim denom As Double = Double.Parse("2.2")
Dim res As Double = num / denom
Console.WriteLine(res)
End Sub End Module
|
|
Imports System
Module MyModule
Sub Main() If (Double.IsNaN("1.2")) Then Console.WriteLine("Not a Number.") End If End Sub End Module
|
2.9.12.Double.IsPositiveInfinity()
|
Imports System
Module MyModule
Sub Main()
If (Double.IsPositiveInfinity("999999999999999999999999999999999")) Then Console.WriteLine("Positive infinity.") End If End Sub End Module
|
2.9.13.Double.IsNegativeInfinity()
|
Imports System
Module MyModule
Sub Main()
If (Double.IsNegativeInfinity("0.0000000000000001")) Then Console.WriteLine("Negative infinity.") End If End Sub End Module
|
2.9.14.Catch OverflowException
|
Public Class Example Public Shared Sub Main()
Dim value As String value = Double.MaxValue.ToString() Try Console.WriteLine(Double.Parse(value)) Catch e As OverflowException Console.WriteLine("{0} is outside the range of the Double type.", value) End Try End Sub End Class
|
2.10.1.Double with/without format
|
public class Test public Shared Sub Main Dim n As Double
n = 12 n /= 7
Console.WriteLine("Without formatting: " & n)
Dim s As String s = String.Format("{0:n3}", n)
Console.WriteLine("With formatting: " & s)
End Sub End class
|
Without formatting: 1.71428571428571
2.10.2.Double format: #,###.###000
|
Public Class Tester Public Shared Sub Main Dim dblNum As Double = 2123.456
Console.WriteLine(dblNum.ToString("#,###.###000"))
End Sub End Class
|
|
Public Class Tester Public Shared Sub Main Dim dblNum As Double = 2123.456
Console.WriteLine(dblNum.ToString("F2"))
End Sub End Class
|
2.11.1.Calculation with Single
|
public class Test public Shared Sub Main Dim Amount As Single Dim Discount As Single Dim DiscAmount As Single
Amount = 24500 Discount = 0.35 DiscAmount = Amount * (1 - Discount) Console.WriteLine("Your price is: $" & DiscAmount)
End Sub End class
|
2.11.2.Single Double MaxValue and Memory Size
|
Public Class Tester Public Shared Sub Main
Dim result As New System.Text.StringBuilder Dim maxSingle As Single = Single.MaxValue Dim maxDouble As Double = Double.MaxValue Dim sizeOfSingle As Integer = Runtime.InteropServices.Marshal.SizeOf(maxSingle.GetType) Dim sizeOfDouble As Integer = Runtime.InteropServices.Marshal.SizeOf(maxDouble.GetType)
result.Append("Memory size of a Single (bytes): ") result.AppendLine(sizeOfSingle) result.Append("Maximum value of a Single: ") result.AppendLine(maxSingle) result.AppendLine()
result.Append("Memory size of a Double (bytes): ") result.AppendLine(sizeOfDouble) result.Append("Maximum value of a Double: ") result.AppendLine(maxDouble)
Console.WriteLine(result.ToString()) End Sub
End Class
|
Memory size of a Single (bytes): 4
Maximum value of a Single: 3.402823E+38
Memory size of a Double (bytes): 8
Maximum value of a Double: 1.79769313486232E+308
|
Public Class Tester Public Shared Sub Main Dim magnitude As Single Dim radians As Single
magnitude = CSng(Math.Sqrt(100 ^ 2 + 120 ^ 2)) radians = CSng(Math.Atan2(100, 123))
Console.WriteLine(magnitude) Console.WriteLine(radians) End Sub
End Class
|
2.11.4.Cast Integer to Short, Double to Single
|
Module Module1
Sub Main() Dim BigInteger As Integer = 10000 Dim LittleInteger As Short
Dim BigFloat As Double = 0.123456789 Dim LittleFloat As Single
LittleInteger = BigInteger LittleFloat = BigFloat
Console.WriteLine(LittleInteger) Console.WriteLine(LittleFloat)
End Sub
End Module
|
|
Module Module1
Sub Main() Dim A As Single 'Dim A As Double For A = 0.01 To 0.1 Step 0.01 If (A = 0.05) Then Console.WriteLine("Reached 0.05") End If Next
Console.WriteLine("Done with loop") End Sub
End Module
|
2.11.6.Show difference precision of Single and Double
|
Module Module1
Sub Main() Dim A As Single = 0.123456789012345 Dim B As Double = 0.123456789012345
Console.WriteLine("Single: " & A) Console.WriteLine("Double: " & B)
End Sub
End Module
|
Double: 0.123456789012345
2.11.7.Pass Single by value and by reference to a Sub
|
public class Test public Shared Sub Main Dim value As Single value = 10 DoubleItByVal(value)
Console.WriteLine(value) value = 10
DoubleItByRef(value) Console.WriteLine(value)
End Sub
Shared Sub DoubleItByVal(ByVal X As Single) X *= 2 End Sub
Shared Sub DoubleItByRef(ByRef X As Single) X *= 2 End Sub
End class
|
2.11.8.Get Epsilon from Single
|
public class Test public Shared Sub Main Console.WriteLine(Single.Epsilon)
End Sub End class
|
2.11.9.Parse(String) method converts an array of strings to equivalent Single values.
|
Module Example Public Sub Main() Dim values() As String = { "100", "(100)", "-123,456,789", "123.45e+6", _ "-Infinity", "-1E-16", Single.MinValue.ToString(), String.Empty } For Each value As String In values Try Dim number As Single = Single.Parse(value) Console.WriteLine("{0} -> {1}", value, number) Catch e As FormatException Console.WriteLine("'{0}' is not in a valid format.", value) Catch e As OverflowException Console.WriteLine("{0} is outside the range of a Single.", value) End Try Next End Sub End Module
|
|
public class Test public Shared Sub Main Dim D1, D2 As Decimal D1 = 10 D2 = 5.7
Console.WriteLine(Decimal.Compare(D1, D2))
End Sub End class
|
|
public class Test public Shared Sub Main Dim D1, D2 As Decimal D1 = 10 D2 = 5.7
Console.WriteLine(Decimal.Divide(D1, D2)) End Sub End class
|
1.7543859649122807017543859649
|
public class Test public Shared Sub Main Console.WriteLine(Decimal.Floor(5.7)) End Sub End class
|
|
public class Test public Shared Sub Main Dim D1, D2 As Decimal D1 = 10 D2 = 5.7
Console.WriteLine(Decimal.GetBits(3).GetValue(0))
End Sub End class
|
2.12.5.Decmimal calculation
|
public class Test public Shared Sub Main Dim Dec1, Dec2 As Decimal Dec1 = 100 Dec2 = 200 Dec1 = Dec1 + Dec2 Console.WriteLine(Dec1) Dec1 = --Dec1 Console.WriteLine(Dec1) Dec1 = ++Dec2 Console.WriteLine(Dec1)
End Sub End class
|
2.12.6.Divide Decimal by double
|
Public Class Tester Public Shared Sub Main
Dim result As New System.Text.StringBuilder Dim maxDecimal As Decimal = Decimal.MaxValue Dim sizeOfDecimal As Integer = Runtime.InteropServices.Marshal.SizeOf(maxDecimal.GetType)
result.Append("Memory size of a Decimal (bytes): ") result.AppendLine(sizeOfDecimal) result.Append("Maximum value of a Decimal: ") result.AppendLine(maxDecimal) result.Append("Divided by one million: ") result.AppendLine(maxDecimal / 1000000D) result.Append("1D / 3D: ") result.AppendLine(1D / 3D)
Console.WriteLine(result.ToString()) End Sub
End Class
|
Memory size of a Decimal (bytes): 16
Maximum value of a Decimal: 79228162514264337593543950335
Divided by one million: 79228162514264337593543.950335
1D / 3D: 0.3333333333333333333333333333
2.12.7.MinValue and MaxValue of Decimal
|
public class Test public Shared Sub Main Dim dNum As Decimal Console.WriteLine("Decimal: " & dNum.MinValue & " to " & dNum.MaxValue) End Sub End class
|
Decimal: -79228162514264337593543950335 to 79228162514264337593543950335
2.12.8.Do calculation between Integer and Decimal
|
public class Test public Shared Sub Main
Dim Meters As Integer Dim Inches As Decimal
Meters = 23 Inches = Meters * 39.37 Console.WriteLine("Meters: " & Meters)
Meters = Meters + 1 Console.WriteLine("Meters: " & Meters)
Meters += 1 Console.WriteLine("Meters: " & Meters)
End Sub End class
|
2.12.9.Converts Decimal numbers to UInt32 values using the explicit Decimal to UInt32 conversion.
|
Module DecimalToU_Int32Demo Public Sub DecimalToU_Int32(argument As Decimal) Dim Int32Value As Object Dim UInt32Value As Object
Try Int32Value = CInt(argument) Catch ex As Exception Int32Value = ex.GetType().Name End Try
Try UInt32Value = CUInt(argument) Catch ex As Exception UInt32Value = ex.GetType().Name End Try
Console.WriteLine(Int32Value) Console.WriteLine(UInt32Value) End Sub
Public Sub Main( ) DecimalToU_Int32( 123d) DecimalToU_Int32(New Decimal(123000, 0, 0, False, 3)) End Sub End Module
|
2.12.10.Converts Decimal numbers to SByte values using the explicit Decimal to SByte conversion.
|
Option Strict On
Module Main Public Sub DecimalToS_Byte(argument As Decimal) Console.WriteLine(argument) Dim sByteValue As Object
Try sByteValue = CByte(argument) Catch ex As Exception sByteValue = ex.GetType().Name End Try
Console.WriteLine(sbyteValue)
End Sub
Public Sub Main( ) DecimalToS_Byte(8d) DecimalToS_Byte(New Decimal(7, 0, 0, false, 3)) End Sub End Module
|
|
public class Test public Shared Sub Main Dim Char1 As Char = "A" Dim Char2 As Char = CChar("A") Dim Char3 As Char = "A"c
Console.WriteLine(Char1 & " " & Char2 & " " & Char3) End Sub End class
|
2.13.2.Declare Char using 'c'
|
Imports System.Collections
public class ConvertToString public Shared Sub Main Dim c As Char = "A"c Dim s As String = "" s = CType(c, String) Console.WriteLine(s) End Sub End class
|
2.13.3.Use CType to convert Char to String
|
Imports System.Collections
public class ConvertToString public Shared Sub Main Dim c As Char = "A"c Dim s As String = "" s = CType(c, String) Console.WriteLine(s) End Sub End class
|
2.13.4.GetUnicodeCategory from Char
|
Imports System
Module GetUnicodeCategorySample
Sub Main() Console.WriteLine(Char.GetUnicodeCategory("a"c)) Console.WriteLine(Char.GetUnicodeCategory("2"c)) Console.WriteLine(Char.GetUnicodeCategory("Upper Case", 6))
End Sub
End Module
|
2.14.1.Passing Char values to Val
|
Option Strict On
Public Module Tester Public Sub Main() ' Console.WriteLine(Val("c"c)) Console.WriteLine(Val("1"c)) Console.WriteLine(Val("-"c)) Console.WriteLine(Val("9"c)) Console.WriteLine()
End Sub End Module
|
2.14.2.Char: IsLetter, IsControl, IsDigit, IsLetterOrDigit, IsLower, IsNumber
|
Public Class Tester Public Shared Sub Main Dim result As New System.Text.StringBuilder Dim counter As Integer Dim testChar As Char Dim testHex As String
For counter = 0 To 127 testChar = Chr(counter) testHex = "\x" & Hex(counter)
If Char.IsLetter(testChar) Then _ result.AppendLine(testHex & " IsLetter") If Char.IsControl(testChar) Then _ result.AppendLine(testHex & " IsControl") If Char.IsDigit(testChar) Then _ result.AppendLine(testHex & " IsDigit") If Char.IsLetterOrDigit(testChar) Then _ result.AppendLine(testHex & " IsLetterOrDigit") If Char.IsLower(testChar) Then _ result.AppendLine(testHex & " IsLower") If Char.IsNumber(testChar) Then _ result.AppendLine(testHex & " IsNumber")
Next counter Console.WriteLine(result) End Sub
End Class
|
2.14.3.Char: IsPunctuation, IsSeparator, IsSymbol, IsUpper, IsWhiteSpace
|
Public Class Tester Public Shared Sub Main Dim result As New System.Text.StringBuilder Dim counter As Integer Dim testChar As Char Dim testHex As String
For counter = 0 To 127 testChar = Chr(counter) testHex = "\x" & Hex(counter)
If Char.IsPunctuation(testChar) Then _ result.AppendLine(testHex & " IsPunctuation") If Char.IsSeparator(testChar) Then _ result.AppendLine(testHex & " IsSeparator") If Char.IsSymbol(testChar) Then _ result.AppendLine(testHex & " IsSymbol") If Char.IsUpper(testChar) Then _ result.AppendLine(testHex & " IsUpper") If Char.IsWhiteSpace(testChar) Then _ result.AppendLine(testHex & " IsWhiteSpace")
Next counter Console.WriteLine(result) End Sub
End Class
|
|
public class Test public Shared Sub Main Dim Char1 As Char
Char1 = "A" If Char.IsDigit(Char1) Then Console.WriteLine("The character is a digit.") Else Console.WriteLine("The character is a letter or symbol.") End If
End Sub End class
|
The character is a letter or symbol.
2.14.5.Remove white space in a string
|
Public Class Tester Public Shared Sub Main Dim source As String = _ Space(17) & "This string had " & Chr(12) & _ StrDup(5, Chr(9)) & "extra whitespace. " & Space(27) Dim thisIsWhiteSpace As Boolean Dim prevIsWhiteSpace As Boolean Dim result As New System.Text.StringBuilder(source.Length) Dim counter As Integer
For counter = 0 To source.Length - 1 prevIsWhiteSpace = thisIsWhiteSpace thisIsWhiteSpace = Char.IsWhiteSpace(source.Chars(counter)) If (thisIsWhiteSpace = False) Then If (prevIsWhiteSpace = True) AndAlso _ (result.Length > 0) Then result.Append(Space(1)) result.Append(source.Chars(counter)) End If Next counter Console.WriteLine(result.ToString()) End Sub
End Class
|
This string had extra whitespace.
|
public class Test public Shared Sub Main
Console.WriteLine(Char.ToUpper("a")) End Sub End class
|
|
Module Module1 Sub Main() Dim strR As String strR = ChrW("123") Console.WriteLine(strR)
End Sub
End Module
|
2.14.8.Demonstrates IsWhiteSpace.
|
imports System
Module IsWhiteSpaceSample
Sub Main()
Dim str As String str = "black matter"
Console.WriteLine(Char.IsWhiteSpace("A"c)) Console.WriteLine(Char.IsWhiteSpace(str, 5)) End Sub End Module
|
|
imports System
Module EqualsSample
Sub Main()
Dim chA As Char chA = "A"c Dim chB As Char chB = "B"c
Console.WriteLine(chA.Equals("A"c)) Console.WriteLine("b"c.Equals(chB))
End Sub
End Module
|
2.14.10.Output ControlChars.Tab
|
Imports System Imports System.Globalization Imports Microsoft.VisualBasic
Public Class MainClass
Public Shared Sub Main() Console.Write(ControlChars.Tab) End Sub End Class
|
2.15.1.NewLine sign: vbNewLine, vbLrLf, vbCr, Environment.NewLine, ControlChars.NewLine
|
Public Class Tester Public Shared Sub Main Dim result As New System.Text.StringBuilder
result.Append("vbNewLine").Append(vbNewLine) result.Append("vbCrLf").Append(vbCrLf) result.Append("vbCr").Append(vbCr) result.Append("vbLf").Append(vbLf) result.Append("Chr(13)").Append(Chr(13)) result.Append("Chr(10)").Append(Chr(10)) result.Append("Chr(13) 'Chr' is not recognized as an internal or external command, operable program or batch file. result.Append("Environment.NewLine").Append(Environment.NewLine) result.Append("ControlChars.CrLf").Append(ControlChars.CrLf) result.Append("ControlChars.NewLine").Append(ControlChars.NewLine)
Console.WriteLine(result.ToString()) End Sub
End Class
|
|
Public Class Tester Public Shared Sub Main Console.WriteLine("a" & vbNewLine & "b") End Sub
End Class
|
2.15.3.Concatenate vbTab with Integer
|
Option Strict On Imports System Module Module1
Sub Main( )
Dim counter As Integer
For counter = 1 To 100 Console.Write("{0} ", counter)
If counter Mod 10 = 0 Then Console.WriteLine(vbTab & counter) End If
Next counter
End Sub
End Module
|
11 12 13 14 15 16 17 18 19 20 20
21 22 23 24 25 26 27 28 29 30 30
31 32 33 34 35 36 37 38 39 40 40
41 42 43 44 45 46 47 48 49 50 50
51 52 53 54 55 56 57 58 59 60 60
61 62 63 64 65 66 67 68 69 70 70
71 72 73 74 75 76 77 78 79 80 80
81 82 83 84 85 86 87 88 89 90 90
91 92 93 94 95 96 97 98 99 100 100
2.15.4.Insert line separator
|
Public Class Tester Public Shared Sub Main Dim result As New System.Text.StringBuilder result.AppendLine("A") result.AppendLine("B") result.AppendLine("C") result.AppendLine("D") result.Append("E")
Dim resultAsString As String = result.ToString() Console.WriteLine(resultAsString)
resultAsString = InsertLine(resultAsString, 3, "(inserted)") Console.WriteLine(resultAsString)
End Sub Public Shared Function InsertLine(ByVal source As String, _ ByVal lineNum As Integer, _ ByVal lineToInsert As String) As String
Dim lineSet() As String Dim atLine As Integer
lineSet = Split(source, vbNewLine)
atLine = lineNum If (atLine < 0) Then atLine = 0 If (atLine >= lineSet.Length) Then lineSet(lineSet.Length - 1) &= vbNewLine & lineToInsert Else lineSet(atLine) = _ lineToInsert & vbNewLine & lineSet(atLine) End If
Return Join(lineSet, vbNewLine) End Function
End Class
|
2.16.1.Define Boolean value and use it in If statement
|
public class Test public Shared Sub Main
Dim blnStatus As Boolean = True Console.WriteLine(blnStatus)
blnStatus = Not blnStatus Console.WriteLine(blnStatus)
If blnStatus Then Console.WriteLine("The status is true.") Else Console.WriteLine("The status is false.") End If
End Sub End class
|
2.16.2.Boolean value calculation: Or, Xor, And, Not
|
public class Test public Shared Sub Main Dim B As Boolean B = False Or True Console.WriteLine(B) B = False Xor False Console.WriteLine(B) B = False And True Console.WriteLine(B) B = Not True Console.WriteLine(B) End Sub End class
|
2.16.3.CBool: convert Integer to Boolean
|
Module Tester Public Sub Main() Dim iBoolean As Integer = -1 Dim bBoolean As Boolean = CBool(iBoolean) Console.WriteLine("Boolean of {0} is {1}", iBoolean, bBoolean) End Sub
End Module
|
2.16.4.CBool(0): convert 0 to Boolean
|
Module Tester Public Sub Main() Dim iBoolean As Integer = -1 Dim bBoolean As Boolean = CBool(iBoolean)
bBoolean = CBool(0) Console.WriteLine("Boolean of 0 is {0}", bBoolean)
End Sub
End Module
|
Public Class Tester Public Shared Sub Main
For counter As Integer = 0 To 15 Console.WriteLine(Hex(counter)) Next counter
End Sub
End Class
|
2.17.2.Hex: output hexadecimal value
|
Option Strict On
Public Module modMain Public Sub Main() Console.WriteLine(Hex("&HE0F1")) Console.WriteLine(Hex("&HFFFF")) End Sub End Module
|
2.17.3.Create a string value that has four hexadecimal digits.
|
Module Example Public Sub Main() Dim byteValues() As Byte = { 12, 163, 255 } For Each byteValue As Byte In byteValues Console.WriteLine(byteValue.ToString("X4")) Next End Sub End Module
|
2.18.1.Bit Shift left and right
|
public class Test public Shared Sub Main '&HFF = the hex value FF, which equals 255, and '1111 1111 in binary Dim numberToBeShifted As Integer = &HFF numberToBeShifted = numberToBeShifted << 4 Console.WriteLine(numberToBeShifted) numberToBeShifted >>= 2 Console.WriteLine(numberToBeShifted)
End Sub End class
|
|
Option Strict On
Public Module SignBit Public Sub Main() Dim negValue As Integer = -1024 ' Save state of sign bit Dim signBit As Integer = negValue And &H80000000 negValue = negValue << 2 ' Clear sign bit negValue = negValue And &H7FFFFFFF ' Restore sign bit negValue = negValue Or signBit Console.WriteLine("Value after shift operation: {0}", negValue) End Sub End Module
|
Value after shift operation: -4096
|
public class Test
public Shared Sub Main Dim X, Y As Complex X = New Complex(1, 4) Y = New Complex(2, 3)
Console.WriteLine((X + Y).ToString) Console.WriteLine((X - Y).ToString) Console.WriteLine((X * Y).ToString) Console.WriteLine((X = Y).ToString) Console.WriteLine((X <> Y).ToString) Console.WriteLine((-X).ToString) Dim abs_x As Double = CDbl(X) Console.WriteLine(abs_x.ToString)
End Sub
End class
Public Class Complex Public Re As Double Public Im As Double
Public Sub New() End Sub Public Sub New(ByVal real_part As Double, ByVal imaginary_part As Double) Re = real_part Im = imaginary_part End Sub
Public Overrides Function ToString() As String Return Re.ToString & " + " & Im.ToString & "i" End Function
Public Shared Operator *(ByVal c1 As Complex, ByVal c2 As Complex) As Complex Return New Complex( _ c1.Re * c2.Re - c1.Im * c2.Im, _ c1.Re * c2.Im + c1.Im * c2.Re) End Operator Public Shared Operator +(ByVal c1 As Complex, ByVal c2 As Complex) As Complex Return New Complex( c1.Re + c2.Re,c1.Im + c2.Im) End Operator Public Shared Operator -(ByVal c1 As Complex, ByVal c2 As Complex) As Complex Return New Complex(c1.Re - c2.Re, c1.Im - c2.Im) End Operator Public Shared Operator =(ByVal c1 As Complex, ByVal c2 As Complex) As Boolean Return (c1.Re = c2.Re) AndAlso (c1.Im = c2.Im) End Operator Public Shared Operator <>(ByVal c1 As Complex, ByVal c2 As Complex) As Boolean Return (c1.Re <> c2.Re) OrElse (c1.Im <> c2.Im) End Operator Public Shared Operator -(ByVal c1 As Complex) As Complex Return New Complex(c1.Im, c1.Re) End Operator Public Shared Narrowing Operator CType(ByVal c1 As Complex) As Double Return System.Math.Sqrt(c1.Re * c1.Re + c1.Im * c1.Im) End Operator End Class
|
|
Public Class Tester
Public Shared Sub Main Dim result As New System.Text.StringBuilder Dim a As ComplexNumber Dim b As ComplexNumber Dim c As ComplexNumber
a = New ComplexNumber(3, 4) b = New ComplexNumber(5, -2) c = a + b
result.AppendLine("Complex Numbers") result.AppendLine("a = " & a.ToString()) result.AppendLine("b = " & b.ToString())
' ----- Addition. c = a + b result.AppendLine("a + b = " & c.ToString())
' ----- Subtraction. c = a - b result.AppendLine("a - b = " & c.ToString())
' ----- Multiplication. c = a * b result.AppendLine("a * b = " & c.ToString())
' ----- Division. c = a / b result.AppendLine("a / b = " & c.ToString())
' ----- Addition as assignment. a += b result.AppendLine("a += b ... a = " & a.ToString())
Console.WriteLine(result.ToString())
End Sub
End Class
Structure ComplexNumber Public Real As Double Public Imaginary As Double
Public Sub New(ByVal realPart As Double, ByVal imaginaryPart As Double) Me.Real = realPart Me.Imaginary = imaginaryPart End Sub
Public Sub New(ByVal sourceNumber As ComplexNumber) Me.Real = sourceNumber.Real Me.Imaginary = sourceNumber.Imaginary End Sub
Public Overrides Function ToString() As String Return Real & "+" & Imaginary & "i" End Function
Public Shared Operator +(ByVal a As ComplexNumber, _ ByVal b As ComplexNumber) As ComplexNumber Return New ComplexNumber(a.Real + b.Real, a.Imaginary + b.Imaginary) End Operator
Public Shared Operator -(ByVal a As ComplexNumber, _ ByVal b As ComplexNumber) As ComplexNumber Return New ComplexNumber(a.Real - b.Real, a.Imaginary - b.Imaginary) End Operator
Public Shared Operator *(ByVal a As ComplexNumber, _ ByVal b As ComplexNumber) As ComplexNumber Return New ComplexNumber(a.Real * b.Real - a.Imaginary * b.Imaginary, _ a.Real * b.Imaginary + a.Imaginary * b.Real) End Operator
Public Shared Operator /(ByVal a As ComplexNumber, _ ByVal b As ComplexNumber) As ComplexNumber Return a * Reciprocal(b) End Operator
Public Shared Function Reciprocal(ByVal a As ComplexNumber) As ComplexNumber Dim divisor As Double
divisor = a.Real * a.Real + a.Imaginary * a.Imaginary If (divisor = 0.0#) Then Throw New DivideByZeroException
Return New ComplexNumber(a.Real / divisor, -a.Imaginary / divisor) End Function End Structure
|
a / b = 0.241379310344828+0.896551724137931i
2.20.1.Define Enum and assign value
|
Module Module1 Enum Temperatures A = 0 B = 32 C = 60 D = 72 E = 212 End Enum Sub Main( ) System.Console.WriteLine("B: {0}",Temperatures.B)
System.Console.WriteLine("E: {0}",Temperatures.E) End Sub End Module
|
2.20.2.Define and use Enum as Integer
|
Option Strict On
<Flags> Public Enum MyValues As Integer AA = 1 BB = 2 CC = 4 DD = 8 End Enum
Public Module modMain Public Sub Main() Dim Computer1 As MyValues = MyValues.AA Or MyValues.BB Console.WriteLine(Computer1.ToString()) End Sub End Module
|
2.20.3.Declare Enum variable
|
Public Enum AccessLevel Clerk Supervisor Administrator End Enum
public class Test public Shared Sub Main
Dim m_AccessLevel As AccessLevel m_AccessLevel = AccessLevel.Supervisor End Sub End class
|
|
Imports System
Module HelloWorld Public Enum CreditCard Visa MasterCard AmericanExpress Discover End Enum Public Sub Main() Dim cc as CreditCard cc = CreditCard.Visa Console.WriteLine(cc) End Sub End Module
|
2.20.5.Assign value to Enum elements
|
Public Enum AccessLevel Clerk = 10 Supervisor Administrator = -1 End Enum
public class Test public Shared Sub Main
Dim m_AccessLevel As AccessLevel m_AccessLevel = AccessLevel.Supervisor End Sub End class
|
2.20.6.Assign value to only one Enum element
|
Public Enum AccessLevel Clerk Supervisor Administrator User = 0 Manager SysAdmin Superuser = SysAdmin End Enum
public class Test public Shared Sub Main
Dim m_AccessLevel As AccessLevel m_AccessLevel = AccessLevel.Supervisor End Sub End class
|
2.20.7.Cast Integer to Enum value
|
Public Enum AccessLevel Clerk Supervisor Administrator User = 0 Manager SysAdmin Superuser = SysAdmin End Enum
public class Test public Shared Sub Main Dim m_AccessLevel As AccessLevel Dim integer_value As Integer = 1
m_AccessLevel = CType(integer_value, AccessLevel)
Dim access_level As AccessLevel = AccessLevel.Clerk Console.WriteLine(access_level.ToString()) End Sub End class
|
2.20.8.Convert Enum to Integer
|
Module Module1 Enum Temperatures A = 0 B = 32 C = 60 D = 72 E = 212 End Enum Sub Main( ) System.Console.WriteLine("B: {0}",CInt(Temperatures.B))
System.Console.WriteLine("E: {0}", CInt(Temperatures.E)) End Sub End Module
|
2.20.9.Enum value duplication
|
Public Enum AccessLevel Level1 Level2 Level3
AliasLevel1 = Level1 AliasLevel2 = Level2 AliasLevel3 = Level3 AliasLevel4 = Level3 End Enum
public class Test public Shared Sub Main Dim access_level As AccessLevel = AccessLevel.Level1 Console.WriteLine(access_level.ToString()) Console.WriteLine(AccessLevel.Level1.ToString()) Console.WriteLine(AccessLevel.Level2.ToString()) Console.WriteLine(AccessLevel.Level3.ToString()) End Sub End class
|
2.20.10.Compare Enum element using logic operator
|
Public Enum workDays Saturday Sunday = 0 Monday Tuesday Wednesday Thursday Friday invalid = -1 End Enum
Public Class Tester Public Shared Sub Main Dim MyDay As WorkDays MyDay = WorkDays.Saturday If MyDay < workDays.FriDay Then Console.WriteLine("It's the weekend.Invalid work day!") End If End Sub End Class
|
It's the weekend.Invalid work day!
2.20.11.Converting an enumerated value to a string.
|
Imports System
Public Class EnumSample Enum Colors Red = 1 Blue = 2 End Enum
Public Shared Sub Main() Dim myColors As Colors = Colors.Red Console.WriteLine("The value of this instance is '{0}'",myColors.ToString()) End Sub End Class
|
2.20.12.Standard Enumeration Format Specifiers
|
Imports System Imports Microsoft.VisualBasic
Class Sample
Public Enum Color Yellow = 1 Blue = 2 Green = 3 End Enum 'Color
Public Shared Sub Main()
' Format a Color enumeration value in various ways. Console.WriteLine("Standard Enumeration Format Specifiers") Console.WriteLine("(G) General:. . . . . . . . . {0:G}" & vbCrLf & _ " (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _ "(F) Flags:. . . . . . . . . . {0:F} (flags or integer)" & vbCrLf & _ "(D) Decimal number: . . . . . {0:D}" & vbCrLf & _ "(X) Hexadecimal:. . . . . . . {0:X}" & vbCrLf, _ Color.Green)
End Sub End Class
|
2.21.1.Demonstrating overflows with and without checking
|
Class Tester
Shared Sub Main()
Try
Dim number1 As Integer = Int32.MaxValue ' 2,147,483,647 Dim number2 As Integer = Int32.MaxValue ' 2,147,483,647 Dim sum As Integer = 0
Console.WriteLine("number1: {0}" & vbCrLf & _ "number2: {1}", number1, number2)
Console.WriteLine("Sum integers in checked context:")
sum = number1 + number2 ' compute sum
Console.WriteLine("Sum after operation: {0}", sum)
Catch overflowExceptionParameter As OverflowException Console.WriteLine(overflowExceptionParameter.ToString())
End Try
End Sub
End Class
|
Sum integers in checked context:
System.OverflowException: Arithmetic operation resulted in an overflow.
2.22.1.Numeric format: {0:N}, {1:E} and G5
|
Public Class Tester Public Shared Sub Main Dim intValue As Integer = 1234567 Dim floatValue As Double = Math.PI Dim result As New System.Text.StringBuilder
result.AppendLine(String.Format("{0} ... {1}", _ intValue, floatValue)) result.AppendLine(String.Format("{0:N} ... {1:E}", _ intValue, floatValue)) result.AppendLine(intValue.ToString("N5") & " ... " & _ floatValue.ToString("G5"))
Console.WriteLine(result.ToString())
End Sub
End Class
|
1234567 ... 3.14159265358979
1,234,567.00 ... 3.141593E+000
1,234,567.00000 ... 3.1416
2.23.1.Boxing and unboxing Integer
|
Option Strict On Imports System
Public Class UnboxingTest Public Shared Sub Main( )
Dim myIntegerVariable As Integer = 123
' Boxing Dim myObjectVariable As Object = myIntegerVariable Console.WriteLine("myObjectVariable: {0}",myObjectVariable.ToString( )) ' unboxing (must be explicit) Dim anotherIntegerVariable As Integer = DirectCast(myObjectVariable, Integer) Console.WriteLine("anotherIntegerVariable: {0}",anotherIntegerVariable) End Sub End Class
|
anotherIntegerVariable: 123
2.24.1.Implicit casting of quotient to an integer
|
Option Strict Off ' must be off to allow implicit casting of quotient to an integer Imports System Module Module1
Sub Main( )
Dim twelve As Integer = 12 Dim five As Integer = 5 Dim intAnswer As Integer Dim doubleAnswer As Double
Console.WriteLine("{0} + {1} = {2}",twelve, five, twelve + five)
Console.WriteLine("{0} - {1} = {2}",twelve, five, twelve - five)
Console.WriteLine("{0} * {1} = {2}",twelve, five, twelve * five) ' integer division intAnswer = twelve \ five doubleAnswer = twelve \ five Console.WriteLine("{0} \ {1} = [integer] {2} [double] {3}", _ twelve, five, intAnswer, doubleAnswer)
' division. Assign result to both an integer and a double ' note, option strict must be off! intAnswer = twelve / five doubleAnswer = twelve / five Console.WriteLine("{0} / {1} = [integer] {2} [double] {3}", _ twelve, five, intAnswer, doubleAnswer)
End Sub
End Module
|
12 \ 5 = [integer] 2 [double] 2
12 / 5 = [integer] 2 [double] 2.4
2.25.1.Use CType to convert from derived class to base class
|
public class Test public Shared Sub Main Dim people As New Collection people.Add(New Employee("A")) people.Add(New Customer("B"))
Dim emp As Employee For Each person As Object In people If TypeOf person Is Employee Then emp = CType(person, Employee) Console.WriteLine(emp.Name) ElseIf TypeOf person Is Customer Then Console.WriteLine(CType(person, Customer).Name) End If Next person End Sub End class
Public Class Employee Public Name As String
Public Sub New(ByVal new_name As String) Name = new_name End Sub
Public Overridable Function IsManager() As Boolean Return False End Function End Class
Public Class Customer Public Name As String
Public Sub New(ByVal new_name As String) Name = new_name End Sub End Class
Public Class Manager Inherits Employee
Public Sub New(ByVal new_name As String) MyBase.new(new_name) End Sub Public Overrides Function IsManager() As Boolean Return True End Function End Class
|
2.26.1.Declare String Variable and assign value
|
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
|
Employee name: James Bond
Employee phone number: 555-1212
|
Option Strict On
Public Module modMain Public Sub Main() Console.WriteLine(String.Empty) End Sub End Module
|
2.26.3.Demonstrating String class constructors
|
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
|
|
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
|
2.26.5.Copy characters from string1 into character Array
|
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
|
2.26.6.String Length property
|
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
|
2.26.7.Demonstrating method GetHashCode of class String
|
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
|
2.26.8.Insert sub string by index
|
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
|
String s3 is 4 characters long.
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)
2.26.9.Insert method returns the resulting string
|
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
|
|
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
|
2.26.11.Get string morse code
|
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
|
2.26.12.String operation timing
|
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
|
First loop took 1734 ms, the second took 0 ms.
2.26.13.Change tab to space
|
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
|
This....is..............a.......tabbed..................string
|
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
|
someDouble.ToString 3.14159265358979
someString.ToString Testing
someDate.ToString 04/07/1776 9:10:11 AM
someDecimal.ToString 0.3333333333333333333333333333
2.26.15.Catch Exception for String.Substring
|
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
|
startIndex cannot be larger than length of string.
Parameter name: startIndex
|
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
|
|
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
|
2.26.18.Make a reference copy
|
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
|
One,Two,Three,Four,Five,Six
One,Two,Three,Four,Five,Six
2.26.19.Check a Credit card number
|
' 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
|
2.26.20.Read String value from Keyboard
|
Module Module1
Sub Main() Dim FirstName As String Console.Write("Name: ") FirstName = Console.ReadLine() Console.WriteLine(FirstName) End Sub
End Module
|
2.27.1.String Concatenate
|
Option Strict On Imports System Class Tester Public Shared Sub Main( ) Dim s1 As String = "abcd" Dim s2 As String = "ABCD"
' concatenation method Dim s3 As String = String.Concat(s1, s2) Console.WriteLine("s3 concatenated from s1 and s2: {0}", s3)
End Sub 'Main End Class 'Tester
|
s3 concatenated from s1 and s2: abcdABCD
2.27.2.Use the overloaded operator
|
Option Strict On Imports System Class Tester Public Shared Sub Main( ) Dim s1 As String = "abcd" Dim s2 As String = "ABCD"
Dim s4 As String = s1 & s2 Console.WriteLine("s4 concatenated from s1 & s2:"+ s4)
End Sub 'Main End Class 'Tester
|
s4 concatenated from s1 & s2: abcdABCD
2.27.3.Create Random String from String array
|
Imports System.Collections
Module Example Public Sub Main() Const WORD_SIZE As Integer = 4 Dim words() As String = { "1234", "5678", "90qw", "qwer" }
Dim keys(WORD_SIZE) As Double Dim letters(WORD_SIZE) As String
Dim rnd As New Random()
For Each word As String In words For ctr As Integer = 0 To word.Length - 1
keys(ctr) = rnd.NextDouble()
letters(ctr) = word.Chars(ctr) Next
Array.Sort(keys, letters, 0, WORD_SIZE, Comparer.Default)
Dim scrambledWord As String = String.Concat(letters(0), letters(1), letters(2), letters(3)) Console.WriteLine(word) Console.WriteLine(scrambledWord) Next End Sub End Module
|
2.27.4.Concat method with a String array.
|
Imports System
Public Class ConcatTest
Public Shared Sub Main() Dim s As String() = {"hello ", "and ", "welcome ", "to ", "this ", "demo! "}
Console.WriteLine(String.Concat(s))
Array.Sort(s) Console.WriteLine(String.Concat(s)) End Sub End Class
|
2.28.String and Byte Char Array
2.28.1.Convert String to Char using System.Convert.ToChar
|
Imports System.Collections
public class ConvertToChar public Shared Sub Main Dim c As Char
c = System.Convert.ToChar("A")
Console.WriteLine(c) End Sub End class
|
2.28.2.ToCharArray methods
|
Imports System.Text
Module Tester
Sub Main() Dim string1 As String = "hello" Dim i As Integer Dim charArray() As Char = string1.ToCharArray()
' display contents of charArray For i = 0 To charArray.Length - 1 Console.WriteLine(charArray(i)) Next End Sub ' Main
End Module
|
2.28.3.Strings And Byte Arrays
|
Public Class Tester Public Shared Sub Main Dim quote As String = "AAAAAasdfasdfasdfasdfasdfasdfasdfadsfasdfadsfads" Dim bytes() As Byte
' ----- Assumed to be all ASCII character. bytes = System.Text.Encoding.UTF8.GetBytes(quote) bytes(46) = 33 ' ASCII exclamation point Console.WriteLine(System.Text.Encoding.UTF8.GetString(bytes))
' ----- Works with all character sets. bytes = System.Text.Encoding.Unicode.GetBytes(quote) bytes(92) = 63 ' ASCII question mark bytes(93) = 0 Console.WriteLine(System.Text.Encoding.Unicode.GetString(bytes)) End Sub End Class
|
AAAAAasdfasdfasdfasdfasdfasdfasdfadsfasdfadsfa!s
AAAAAasdfasdfasdfasdfasdfasdfasdfadsfasdfadsfa?s
2.28.4.String and char array
|
Public Class Tester Public Shared Sub Main Dim quote As String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" Dim charArray() As Char = CType(quote, Char()) charArray(6) = "!"c Dim result As String = New String(charArray) Console.WriteLine(result) End Sub End Class
|
aaaaaa!aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
2.28.5.Reorder chars in a string
|
Public Class Tester Public Shared Sub Main Dim counter As Integer Dim position As Integer Dim holdChar As Char Dim jumbleMethod As New Random Dim quote As String = "abcedfg"
Dim chars() As Char = CType(quote, Char())
For counter = 0 To chars.Length - 1 position = jumbleMethod.Next Mod chars.Length holdChar = chars(counter) chars(counter) = chars(position) chars(position) = holdChar Next counter
Dim result As String = New String(chars) Console.WriteLine(result)
End Sub End Class
|
2.28.6.Loop through characters in string and display reversed
|
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) {}
For i = string1.Length - 1 To 0 Step -1 Console.WriteLine(string1.Chars(i)) Next
End Sub ' Main
End Module
|
2.28.7.Use IndexOf to locate a character in a string
|
Module Tester
Sub Main() Dim letters As String = "abcdefghijklmabcdefghijklm" Dim searchLetters As Char() = New Char() {"c"c, "a"c, "$"c}
Console.WriteLine(letters.IndexOf("c"c))
Console.WriteLine(letters.IndexOf("a"c, 1))
Console.WriteLine(letters.IndexOf("$"c, 3, 5))
End Sub ' Main
End Module ' modIndexMethods
|
2.28.8.Use LastIndexOf to find a character in a string
|
Module Tester
Sub Main() Dim letters As String = "abcdefghijklmabcdefghijklm" Dim searchLetters As Char() = New Char() {"c"c, "a"c, "$"c}
Console.WriteLine(letters.LastIndexOf("c"c))
Console.WriteLine(letters.LastIndexOf("a"c, 25))
Console.WriteLine(letters.LastIndexOf("$"c, 15, 5)) End Sub
End Module
|
2.28.9.Converts a substring within a string to an array of characters, then enumerates and displays the elements of the array.
|
' Sample for String.ToCharArray(Int32, Int32) Imports System
Class Sample
Public Shared Sub Main() Dim str As String = "012wxyz789" Dim arr() As Char
arr = str.ToCharArray(3, 4) Console.Write("The letters in '{0}' are: '", str) Console.Write(arr) Console.WriteLine("Each letter in '{0}' is:", str) Dim c As Char For Each c In arr Console.WriteLine(c) Next c End Sub End Class
|
|
Module Test Public Sub Main() Dim sMonths() As String = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", Oct", "Nov", "Dec"}
Console.WriteLine("Eleventh month of the year = {0}", sMonths(10))
End Sub End Module
|
Eleventh month of the year = Nov
2.29.2.Use For Each Loop to output a String array
|
Public Class Tester Public Shared Sub Main Dim fruitArray() As String = {"Oranges", "Apples", "Grapes", "Bananas", "Blueberries"}
For Each fruit As String In fruitArray Console.WriteLine(fruit) Next fruit
End Sub
End Class
|
2.29.3.Array.Reverse a string array
|
Imports System.Collections
public class Test public Shared Sub Main Dim StringArray() As String = {"This", "is", "a", "test"}
Array.Reverse(StringArray) Dim E As IEnumerator = StringArray.GetEnumerator() While (E.MoveNext()) Console.WriteLine(E.Current()) End While
End Sub End class
|
2.29.4.Array.Sort a string array
|
Imports System.Collections
public class Test public Shared Sub Main Dim StringArray() As String = {"This", "is", "a", "test"} Array.Sort(StringArray) Dim E As IEnumerator = StringArray.GetEnumerator() While (E.MoveNext()) Console.WriteLine(E.Current()) End While
End Sub End class
|
2.29.5.Two dimensional string array
|
public class Test public Shared Sub Main
Dim str_values(,,) As String = _ { _ { _ {"000", "001", "002"}, _ {"010", "011", "012"} _ }, _ { _ {"100", "101", "102"}, _ {"110", "111", "112"} _ } _ } Console.WriteLine("") For i As Integer = 0 To 1 For j As Integer = 0 To 1 For k As Integer = 0 To 2 Console.Write(str_values(i, j, k) & " ") Next k Next j Console.WriteLine("") Next i
End Sub End class
|
2.29.6.Store data in a multivalue array
|
Public Class Tester Public Shared Sub Main Dim multiValue(2)() As String Dim counter1 As Integer Dim counter2 As Integer
' ----- Build the multivalue array. multiValue(0) = New String() {"alpha", "beta", "gamma"} multiValue(1) = New String() {"A", "B", "C", "D", "E", "F", "G", "H"} multiValue(2) = New String() {"Yes", "No"}
' ----- Format the array for display. For counter1 = 0 To multiValue.Length - 1 For counter2 = 0 To multiValue(counter1).Length - 1 Console.WriteLine(multiValue(counter1)(counter2)) Next counter2 Console.WriteLine("") Next counter1 End Sub
End Class
|
2.30.1.Change string to upper case by using UCase
|
Class Tester Shared Sub Main() Dim userInput As String userInput = " asdf "
Console.WriteLine(UCase(userInput)) End Sub
End Class
|
2.30.2.Change string to lower case and upper case
|
Public Class Tester Public Shared Sub Main Dim quote As String = "AbCdEfG" Dim result As New System.Text.StringBuilder
result.AppendLine("Original: " & quote) result.AppendLine("Upper Case: " & quote.ToUpper()) result.AppendLine("Lower Case: " & quote.ToLower()) result.AppendLine("Mixed Case: " & MixedCase(quote))
Console.WriteLine(result.ToString()) End Sub Public Shared Function MixedCase(ByVal origText As String) As String Dim counter As Integer Dim textParts() As String = Split(origText, " ")
For counter = 0 To textParts.Length - 1 If (textParts(counter).Length > 0) Then _ textParts(counter) = _ UCase(Microsoft.VisualBasic.Left( _ textParts(counter), 1)) & _ LCase(Mid(textParts(counter), 2)) Next counter
Return Join(textParts, " ") End Function
End Class
|
2.30.3.Capitalize the first letter
|
Public Class Tester Public Shared Sub Main Dim quote As String = "AbCdEfG" Dim result As New System.Text.StringBuilder
result.AppendLine("Original: " & quote) result.AppendLine("Upper Case: " & quote.ToUpper()) result.AppendLine("Lower Case: " & quote.ToLower()) result.AppendLine("Mixed Case: " & MixedCase(quote))
Console.WriteLine(result.ToString()) End Sub Public Shared Function MixedCase(ByVal origText As String) As String Dim counter As Integer Dim textParts() As String = Split(origText, " ")
For counter = 0 To textParts.Length - 1 If (textParts(counter).Length > 0) Then _ textParts(counter) = _ UCase(Microsoft.VisualBasic.Left( _ textParts(counter), 1)) & _ LCase(Mid(textParts(counter), 2)) Next counter
Return Join(textParts, " ") End Function
End Class
|
2.31.1.Comparing strings: Equals, =, String.Equals() and CompareTo
|
Module Tester
Sub Main() Dim string1 As String = "hello" Dim string2 As String = "good bye" Dim string3 As String = "Happy Birthday" Dim string4 As String = "happy birthday" Dim output As String Dim quotes As Char = ChrW(34)
If (string1.Equals("hello")) Then Console.WriteLine("string1 equals hello") Else Console.WriteLine("not equal ") End If
' test for equality with = If string1 = "hello" Then Console.WriteLine("string1 equals " & quotes & "hello" & quotes ) Else Console.WriteLine("string1 does not equal " & quotes & "hello" & quotes) End If
If (String.Equals(string3, string4)) Then Console.WriteLine("string3 equals string4") Else Console.WriteLine("string3 does not equal string4") End If
' test CompareTo Console.WriteLine("string1.CompareTo(string2) is " & _ string1.CompareTo(string2) & vbCrLf & _ "string2.CompareTo(string1) is " & _ string2.CompareTo(string1) & vbCrLf & _ "string1.CompareTo(string1) is " & _ string1.CompareTo(string1) & vbCrLf & _ "string3.CompareTo(string4) is " & _ string3.CompareTo(string4) & vbCrLf & _ "string4.CompareTo(string3) is " & _ string4.CompareTo(string3))
End Sub ' Main
End Module
|
string3 does not equal string4
string1.CompareTo(string2) is 1
string2.CompareTo(string1) is -1
string1.CompareTo(string1) is 0
string3.CompareTo(string4) is 1
string4.CompareTo(string3) is -1
2.31.2.String Equals with overloaded operator, member method and static member method
|
Option Strict On Imports System
Class Tester
Public Shared Sub Main( ) Dim s1 As String = "abcd" Dim s2 As String = "ABCD"
' the String copy method Dim s5 As String = String.Copy(s2) Console.WriteLine("s5 copied from s2: {0}", s5)
' copy with the overloaded operator Dim s6 As String = s5 Console.WriteLine("s6 = s5: {0}", s6)
' member method Console.WriteLine("Does s6.Equals(s5)?: {0}", s6.Equals(s5))
' shared method Console.WriteLine("Does Equals(s6,s5)?: {0}", _ String.Equals(s6, s5))
End Sub 'Main End Class 'Tester
|
Does s6.Equals(s5)?: True
Does Equals(s6,s5)?: True
2.31.3.String Compare with case sensitive and insensitive
|
Class Tester
Shared Sub Main( ) Dim s1 As [String] = "abcd" Dim s2 As [String] = "ABCD" Dim result As Integer
result = [String].Compare(s1, s2) Console.WriteLine("compare s1: {0}, s2: {1}, result: {2}" _ & Environment.NewLine, s1, s2, result)
result = [String].Compare(s1, s2, True) Console.WriteLine("Compare insensitive. result: {0}" _ & Environment.NewLine, result) End Sub End Class
|
compare s1: abcd, s2: ABCD, result: -1
Compare insensitive. result: 0
2.31.4.Compare String value in If statement
|
Module Module1
Sub Main()
Dim Language As String = "English"
If (Language = "English") Then Console.WriteLine("Hello, world!") ElseIf (Language = "Spanish") Then Console.WriteLine("Hola, mundo") End If
End Sub
End Module
|
2.31.5.Whether a string is the prefix or suffix of another string.
|
Imports System Imports System.Globalization
Public Class SamplesCompareInfo
Public Shared Sub Main() Dim myStr1 As [String] = "this" Dim myStr2 As [String] = "is" Dim myXfix As [String] = "th"
' Uses the CompareInfo property of the InvariantCulture. Dim myComp As CompareInfo = CultureInfo.InvariantCulture.CompareInfo
' Determines whether myXfix is a prefix of "calle" and "llegar". Console.WriteLine("IsPrefix( {0}, {1} ) : {2}", myStr1, myXfix, myComp.IsPrefix(myStr1, myXfix)) Console.WriteLine("IsPrefix( {0}, {1} ) : {2}", myStr2, myXfix, myComp.IsPrefix(myStr2, myXfix))
' Determines whether myXfix is a suffix of "calle" and "llegar". Console.WriteLine("IsSuffix( {0}, {1} ) : {2}", myStr1, myXfix, myComp.IsSuffix(myStr1, myXfix)) Console.WriteLine("IsSuffix( {0}, {1} ) : {2}", myStr2, myXfix, myComp.IsSuffix(myStr2, myXfix))
End Sub
End Class
|
2.31.6.Use the CompareTo method with another String.
|
Imports System
Public Class MainClass
Public Shared Sub Main() Dim strFirst As String = "Goodbye"
Console.WriteLine(CompareStrings(strFirst, strFirst)) End Sub Private Shared Function CompareStrings(str1 As String, str2 As String) As String Dim cmpVal As Integer = str1.CompareTo(str2) If cmpVal = 0 Then Return "The strings have the same value!" Else If cmpVal > 0 Then Return "The first string is greater than the second string!" Else Return "The second string is greater than the first string!" End If End If End Function End Class
|
2.31.7.Use String.Compare to check if a URI is a file URI
|
Public Class SamplesCompareInfo
Public Shared Sub Main()
End Sub
Shared Function IsFileURI(ByVal path As String) As Boolean If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then Return True Else Return False End If
End Function End Class
|
2.31.8.Compare two strings using different CompareOptions settings.
|
Imports System Imports System.Globalization
Public Class SamplesCompareInfo
Public Shared Sub Main() Dim myStr1 As [String] = "B" Dim myStr2 As [String] = "b" Dim myComp As CompareInfo = CultureInfo.InvariantCulture.CompareInfo
Console.WriteLine(" With no CompareOptions : {0}", myComp.Compare(myStr1, myStr2)) Console.WriteLine(" With None : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.None)) Console.WriteLine(" With Ordinal : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.Ordinal)) Console.WriteLine(" With StringSort : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.StringSort)) Console.WriteLine(" With IgnoreCase : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreCase)) Console.WriteLine(" With IgnoreSymbols : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreSymbols)) Console.WriteLine(" With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreCase Or CompareOptions.IgnoreSymbols))
End Sub End Class
|
2.32.1.Use the String Copy method
|
Option Strict On Imports System
Class Tester Public Shared Sub Main( ) Dim s1 As String = "abcd" Dim s2 As String = "ABCD"
' the String copy method Dim s5 As String = String.Copy(s2) Console.WriteLine("s5 copied from s2: {0}", s5)
End Sub 'Main End Class 'Tester
|
2.32.2.Use the overloaded operator (=) to copy string
|
Option Strict On Imports System
Class Tester Public Shared Sub Main( ) Dim s1 As String = "abcd" Dim s2 As String = "ABCD"
Dim s6 As String = s1 Console.WriteLine("s6 = s1: {0}", s6)
End Sub 'Main End Class 'Tester
|
2.33.1.Demonstrating StartsWith and EndsWith methods
|
Module Tester
Sub Main() Dim strings As String() Dim output As String = "" Dim i As Integer Dim quotes As Char = ChrW(34)
strings = New String() {"started", "starting", _ "ended", "ending"}
For i = 0 To strings.GetUpperBound(0) If strings(i).StartsWith("st") Then Console.WriteLine(" starts with st") End If
Next
For i = 0 To strings.GetUpperBound(0) If strings(i).EndsWith("ed") Then Console.WriteLine(" ends with ed" ) End If
Next
End Sub ' Main
End Module
|
2.33.2.Return the index of the string
|
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"
Console.WriteLine("s3: {0}", s3) Console.Write("The first occurrence of a ") Console.WriteLine(s3.IndexOf("a"))
End Sub 'Main End Class 'Tester
|
The first occurrence of a -1
2.33.3.Use IndexOf to locate a substring in a string
|
Module Tester
Sub Main() Dim letters As String = "abcdefghijklmabcdefghijklm" Dim searchLetters As Char() = New Char() {"c"c, "a"c, "$"c}
Console.WriteLine(letters.IndexOf("def"))
Console.WriteLine(letters.IndexOf("def", 7))
Console.WriteLine(letters.IndexOf("hello", 5, 15)) End Sub
End Module
|
2.33.4.Use LastIndexOf to find a substring in a string
|
Module Tester
Sub Main() Dim letters As String = "abcdefghijklmabcdefghijklm" Dim searchLetters As Char() = New Char() {"c"c, "a"c, "$"c}
Console.WriteLine(letters.LastIndexOf("def"))
Console.WriteLine(letters.LastIndexOf("def", 25))
Console.WriteLine(letters.LastIndexOf("hello", 20, 15)) End Sub
End Module
|
2.33.5.Use IndexOfAny to find first occurrence of character in array
|
Module Tester
Sub Main() Dim letters As String = "abcdefghijklmabcdefghijklm" Dim searchLetters As Char() = New Char() {"c"c, "a"c, "$"c}
Console.WriteLine("First occurrence of ""c""," & _ " ""a"" or ""$"" is located at " & _ letters.IndexOfAny(searchLetters))
Console.WriteLine("First occurrence of ""c"", ""a"" or " & _ """$"" is located at " & _ letters.IndexOfAny(searchLetters, 7))
Console.WriteLine("First occurrence of ""c"", ""a"" or " & _ """$"" is located at " & _ letters.IndexOfAny(searchLetters, 20, 5)) End Sub
End Module
|
First occurrence of "c", "a" or "$" is located at 0
First occurrence of "c", "a" or "$" is located at 13
First occurrence of "c", "a" or "$" is located at -1
2.33.6.Use LastIndexOfAny to find first occurrence of character in array
|
Module Tester
Sub Main() Dim letters As String = "abcdefghijklmabcdefghijklm" Dim searchLetters As Char() = New Char() {"c"c, "a"c, "$"c}
Console.WriteLine("Last occurrence of ""c""," & _ " ""a"" or ""$"" is located at " & _ letters.LastIndexOfAny(searchLetters))
Console.WriteLine("Last occurrence of ""c"", ""a"" or " & _ """$"" is located at " & _ letters.LastIndexOfAny(searchLetters, 1))
Console.WriteLine("Last occurrence of ""c"", ""a"" or " & _ """$"" is located at " & _ letters.LastIndexOfAny(searchLetters, 25, 5)) End Sub
End Module
|
Last occurrence of "c", "a" or "$" is located at 15
Last occurrence of "c", "a" or "$" is located at 0
Last occurrence of "c", "a" or "$" is located at -1
2.33.7.String Index of any
|
public class Test public Shared Sub Main Dim s1 As New String("Greeting") Console.WriteLine(s1.IndexOfAny("tin")) End Sub End class
|
2.33.8.Use the LastIndexOf(Char) method to find the last directory separator character in a string
|
Imports System.IO
Public Module Test Public Sub Main() Dim filename As String
filename = ExtractFilename("C:\delegate.txt") Console.WriteLine(filename)
End Sub
Public Function ExtractFilename(filepath As String) As String If filepath.Trim().EndsWith("\") Then Return String.Empty Dim position As Integer = filepath.LastIndexOf("\"c) If position = -1 Then If File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath) Then Return filepath Else Return String.Empty End If Else If File.Exists(filepath) Then Return filepath.Substring(position + 1) Else Return String.Empty End If End If End Function End Module
|
|
Imports System
Public Class EndsWithTest
Public Shared Sub Main() Dim strSource As String() = { "<b>This is bold text</b>","wrong>"}
Dim s As String For Each s In strSource Console.WriteLine(StripEndTags(s)) Next s End Sub Private Shared Function StripEndTags(item As String) As String If item.Trim().EndsWith(">") Then Dim lastLocation As Integer = item.LastIndexOf("</") If lastLocation >= 0 Then item = item.Substring(0, lastLocation) End If End If Return Item End Function End Class
|
2.33.10.Find the index of the last occurrence of any character in the string "is" within another string.
|
Imports System
Class Sample Public Shared Sub Main() Dim str As String = "this is a test." Dim start As Integer Dim at As Integer Dim target As String = "is" Dim anyOf As Char() = target.ToCharArray()
at = str.LastIndexOfAny(anyOf) If at > - 1 Then Console.Write(at) Else Console.Write("(not found)") End If End Sub End Class
|
2.33.11.IsMatch(String) determines whether a string is a valid to Regular expression
|
Imports System.Text.RegularExpressions
Module Example Public Sub Main() Dim rgx As New Regex("^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$") Console.WriteLine(rgx.IsMatch("1298-673-4192"))
End Sub End Module
|
2.34.1.String.Format: {0,10:p}
|
Public Class Tester Public Shared Sub Main
Console.WriteLine(String.Format("{0,10:p}", 0.32))
End Sub End Class
|
2.34.2.String.Format: {0:#,### ; #.## ,00##,00}
|
Public Class Tester Public Shared Sub Main
Console.WriteLine(String.Format("{0:#,### ; #.## ,00##,00}",1232.2345))
End Sub End Class
|
2.34.3.String.Format: {0:##.## ; -##.# ; 0.0#} (2)
|
Public Class Tester Public Shared Sub Main
Console.WriteLine(String.Format("{0:##.## ; -##.# ; 0.0#}", -1235.33))
End Sub End Class
|
2.34.4.String.Format: {0:##.## ; (##.00) ; 0.0#} (3)
|
Public Class Tester Public Shared Sub Main
Console.WriteLine(String.Format("{0:##.## ; (##.00) ; 0.0#}", 0))
End Sub End Class
|
2.34.5.String format: {0, 1:D}
|
Module Module1
Sub Main() Dim A As Double = 1.23456789 Console.WriteLine("{0, 1:D} {1, 2:D} {2, 3:D}", 1, 2, 3)
End Sub
End Module
|
2.34.6.String format: {0, 7:F1}
|
Module Module1
Sub Main() Dim A As Double = 1.23456789 Console.WriteLine("{0, 7:F1} {1, 7:F3} {2, 7:F5}", A, A, A)
End Sub
End Module
|
2.34.7.String format: {0, 0:#.#}, {0, 0:#.###}, {0, 0:#.#####} (4)
|
Module Module1
Sub Main() Dim A As Double = 1.23456789 Console.WriteLine("{0, 0:#.#}", A) Console.WriteLine("{0, 0:#.###}", A) Console.WriteLine("{0, 0:#.#####}", A)
End Sub
End Module
|
|
public class Test public Shared Sub Main Dim strLeftPad, strRightPad As String
strLeftPad = "[" & "Visual Basic Express".PadLeft(28) & "]" strRightPad = "[" & "Visual Basic Express".PadRight(28) & "]" Console.WriteLine(strLeftPad & vbCrLf & strRightPad)
strLeftPad = "[" & "Visual Basic Express".PadLeft(28, "@") & "]" strRightPad = "[" & "Visual Basic Express".PadRight(28, ".") & "]" Console.WriteLine(strLeftPad & vbCrLf & strRightPad)
End Sub End class
|
[@@@@@@@@Visual Basic Express]
[Visual Basic Express........]
2.35.2.PadLeft, PadRight and PadCenter
|
Public Class Tester Public Shared Sub Main Dim content1 As String Dim content2 As String Dim content3 As String Dim content4 As String
content1 = "Not padded" content2 = "PadLeft".PadLeft(50) content3 = "PadRight".PadRight(50) content4 = "PadCenter" content4 = content4.PadLeft((50 + _ content4.Length) \ 2).PadRight(50) Console.WriteLine(String.Format("{0}{4}{1}{4}{2}{4}{3}", _ content1, content2, content3, content4, vbNewLine))
End Sub
End Class
|
2.35.3.PadLeft, PadRight and PadCenter with dot
|
Public Class Tester Public Shared Sub Main Dim content1 As String Dim content2 As String Dim content3 As String Dim content4 As String
content1 = "Not padded" content2 = "PadLeft".PadLeft(50, "."c) content3 = "PadRight".PadRight(50, "."c) content4 = "PadCenter" content4 = content4.PadLeft((50 + content4.Length) \ 2, _ "."c).PadRight(50, "."c) Console.WriteLine(String.Format("{0}{4}{1}{4}{2}{4}{3}", _ content1, content2, content3, content4, vbNewLine))
End Sub
End Class
|
...........................................PadLeft
PadRight..........................................
....................PadCenter.....................
2.36.1.Replace a sub string with 'Replace'
|
Class Tester Shared Sub Main() Dim userInput As String userInput = " asdf "
Console.WriteLine(Replace(userInput, "f", "")) End Sub
End Class
|
2.36.2.Replace substring with another substring
|
public class Test public Shared Sub Main Dim s1 As New String("Greeting") s1 = s1.Replace("e", "i") Console.WriteLine(s1) End Sub End class
|
2.37.1.String split by using the Split, String.Split()
|
Public Class Tester Public Shared Sub Main Dim quote As String = "The important thing is not to " & _ "stop questioning. --Albert Einstein" Dim strArray1() As String = Split(quote, "ing") Dim strArray2() As String = quote.Split(CChar("ing")) Dim counter As Integer
For counter = 0 To strArray1.Length - 1 Console.WriteLine(strArray1(counter)) Next counter
For counter = 0 To strArray2.Length - 1 Console.WriteLine(strArray2(counter)) Next counter End Sub
End Class
|
2.37.2.Use Regular Expression to Split string
|
Imports System Imports System.Text Imports System.Text.RegularExpressions
Class Tester Public Shared Sub Main( ) Dim s1 As String = "One,Two,Three Four" Dim theRegex As New Regex(" |, |,") Dim sBuilder As New StringBuilder( ) Dim id As Integer = 1
Dim subString As String For Each subString In theRegex.Split(s1) id = id + 1 sBuilder.AppendFormat("{0}: {1}" & Environment.NewLine, id, subString) Next subString Console.WriteLine("{0}", sBuilder) End Sub End Class
|
|
Option Strict On Imports System
Class Tester
Public Shared Sub Main( ) Dim s1 As String = "One,Two,Three Liberty Associates, Inc."
Const Space As Char = " "c Const Comma As Char = ","c
Dim delimiters( ) As Char = {Space, Comma}
Dim output As String = "" Dim ctr As Integer = 0
Dim resultArray As String( ) = s1.Split(delimiters)
Dim subString As String For Each subString In resultArray ctr = ctr + 1 output &= ctr.ToString( ) output &= ": " output &= subString output &= Environment.NewLine Next subString Console.WriteLine(output) End Sub 'Main End Class 'Tester
|
2.37.4.Use the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.
|
Imports System
Class Sample Public Shared Sub Main() Dim s1 As String = ",ONE,,TWO,,,THREE,," Dim s2 As String = "[stop]" & _ "ONE[stop][stop]" & _ "TWO[stop][stop][stop]" & _ "THREE[stop][stop]" Dim charSeparators() As Char = {","c} Dim stringSeparators() As String = {"[stop]"} Dim result() As String
result = s1.Split(charSeparators, StringSplitOptions.None) Show(result)
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries) Show(result)
result = s1.Split(charSeparators, 2, StringSplitOptions.None) Show(result)
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries) Show(result)
result = s2.Split(stringSeparators, StringSplitOptions.None) Show(result)
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries) Show(result)
result = s2.Split(stringSeparators, 2, StringSplitOptions.None) Show(result)
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries) Show(result)
End Sub
Public Shared Sub Show(ByVal entries() As String) Console.WriteLine("The return value contains these {0} elements:", entries.Length) Dim entry As String For Each entry In entries Console.Write("<{0}>", entry) Next entry Console.Write(vbCrLf & vbCrLf)
End Sub End Class
|
2.38.1.Passing String values to Val
|
Option Strict On
Public Module Tester Public Sub Main() ' Console.WriteLine(Val("913.3")) Console.WriteLine(Val("131AC57")) Console.WriteLine(Val("-132.23")) Console.WriteLine(Val("+1203.22")) Console.WriteLine(Val("A0545")) Console.WriteLine()
End Sub End Module
|
2.38.2.Passing formatted numeric values to Val
|
Option Strict On
Public Module Tester Public Sub Main() ' Passing formatted numeric values to Val Console.WriteLine(Val("$1034.51")) Console.WriteLine(Val("1,032.54")) End Sub End Module
|
2.38.3.IsNumeric, IsDate, IsNothing
|
Public Class Tester Public Shared Sub Main Dim theData As String = Nothing Dim result As New System.Text.StringBuilder
' ----- Format nothing. result.AppendLine(String.Format( _ "IsNumeric({0}) ... {1}", theData, IsNumeric(theData))) result.AppendLine(String.Format( _ "IsDate({0}) ... {1}", theData, IsDate(theData))) result.AppendLine(String.Format( _ "IsNothing({0}) ... {1}", theData, IsNothing(theData))) result.AppendLine()
' ----- Format a number in a string. theData = "-12.345" result.AppendLine(String.Format( _ "IsNumeric({0}) ... {1}", theData, IsNumeric(theData))) result.AppendLine(String.Format( _ "IsDate({0}) ... {1}", theData, IsDate(theData))) result.AppendLine(String.Format( _ "IsNothing({0}) ... {1}", theData, IsNothing(theData))) result.AppendLine()
' ----- Format a date in a string. theData = "July 17, 2007" result.AppendLine(String.Format( _ "IsNumeric({0}) ... {1}", theData, IsNumeric(theData))) result.AppendLine(String.Format( _ "IsDate({0}) ... {1}", theData, IsDate(theData))) result.Append(String.Format( _ "IsNothing({0}) ... {1}", theData, IsNothing(theData)))
Console.WriteLine(result.ToString())
End Sub End Class
|
IsNumeric(-12.345) ... True
IsDate(-12.345) ... False
IsNothing(-12.345) ... False
IsNumeric(July 17, 2007) ... False
IsDate(July 17, 2007) ... True
IsNothing(July 17, 2007) ... False
2.38.4.Duplicate a string
|
Public Class Tester Public Shared Sub Main Console.WriteLine(StrDup(30, "-")) End Sub
End Class
|
------------------------------
2.38.5.Get string index by using InStr
|
Class Tester Shared Sub Main() Dim userInput As String userInput = " asdf "
Console.WriteLine(InStr(userInput, "f")) End Sub
End Class
|
2.38.6.CStr: Convert Double to String
|
Public Class Tester Public Shared Sub Main Dim x As Double
x = 12345678901234567890D
Console.WriteLine(CStr(x))
End Sub
End Class
|
2.38.7.Len: get string length
|
Public Class Tester Public Shared Sub Main Console.WriteLine(Len("txtString1.Text")) End Sub
End Class
|
|
Public Class Tester Public Shared Sub Main Dim MyString As String, YourString As String
MyString = "asdf" YourString = "fdsa" Console.WriteLine(InStr(2, MyString, YourString)) End Sub
End Class
|
|
Public Module modMain Public Sub Main() Dim title As String = "Mr." Dim name As Object = DBNull.Value Dim addressLine1 As String = title & " " & name If IsDBNull(addressLine1) Then Console.WriteLine("Null value") Else Console.WriteLine(addressLine1) End If End Sub End Module
|
2.38.10.Microsoft.VisualBasic.Left
|
public class Test public Shared Sub Main Dim strName As String = "Visual Basic Express"
If Microsoft.VisualBasic.Left(strName, 3) = "Vis" Then Console.WriteLine("True") If strName.StartsWith("Vis") Then Console.WriteLine("True")
End Sub End class
|
|
public class Test public Shared Sub Main Dim str1, str2 As String
str1 = "some text" str2 = str1 str2 = String.Copy(str1) Console.WriteLine(str1 & vbCrLf & str2)
End Sub End class
|
2.38.12.Use String.Concat to concatenate two strings
|
public class Test public Shared Sub Main Dim aryStrings() As String = {"string1", "string2", "string3", "string4"} Dim strLongString As String
strLongString = String.Concat(aryStrings) Console.WriteLine(strLongString)
End Sub End class
|
string1string2string3string4
|
Public Class Tester Public Shared Sub Main Console.WriteLine( Format(123, "c") ) End Sub
End Class
|
2.38.14.String handling function: Len
|
Module Tester Public Sub Main() Dim sHello As String = "Hello World" Console.WriteLine("Original string: {0}", sHello) Console.WriteLine("Length of string (Len(sHello)): {0}", Len(sHello)) End Sub
End Module
|
Original string: Hello World
Length of string (Len(sHello)): 11
2.38.15.Left: get characters from left
|
Module Tester Public Sub Main() Dim sHello As String = "Hello World" Console.WriteLine("Original string: {0}", sHello) Console.WriteLine("Leftmost two characters (Left(sHello, 2)): {0}", Left(sHello, 2)) End Sub
End Module
|
Original string: Hello World
Leftmost two characters (Left(sHello, 2)): He
VB.Net Tutorial » Data Type » String Functions
|
|
|
2.38.16.Right: get characters from right
|
Module Tester Public Sub Main() Dim sHello As String = "Hello World" Console.WriteLine("Original string: {0}", sHello) Console.WriteLine("Rightmost four characters (Right(sHello, 4)): {0}", Right(sHello, 4)) End Sub
End Module
|
|
Original string: Hello World
Rightmost four characters (Right(sHello, 4)): orld
|
2.38.17.Mid(string, 4, 5): get sub string from middle
|
Module Tester Public Sub Main() Dim sHello As String = "Hello World" Console.WriteLine("Original string: {0}", sHello) Console.WriteLine("From middle of string (Mid(sHello, 4, 5)): {0}", Mid(sHello, 4, 5)) End Sub
End Module
|
Original string: Hello World
From middle of string (Mid(sHello, 4, 5)): lo Wo
2.38.18.Mid(string, 7): get sub string from start
|
Module Tester Public Sub Main() Dim sHello As String = "Hello World" Console.WriteLine("Original string: {0}", sHello) Console.WriteLine("Starting with character (Mid(sHello, 7)): {0}", Mid(sHello, 7)) End Sub
End Module
|
Original string: Hello World
Starting with character (Mid(sHello, 7)): World
2.38.19.Instr: find character in a string
|
Module Tester Public Sub Main() Dim sHello As String = "Hello World" Console.WriteLine("Original string: {0}", sHello) Console.WriteLine("Find character (Instr(1, sHello, 'l')) : {0}", InStr(1, sHello, "l")) End Sub
End Module
|
Original string: Hello World
Find character (Instr(1, sHello, 'l')) : 3
2.38.20.Instr: find sub string a in a string
|
Module Tester Public Sub Main() Dim sHello As String = "Hello World" Console.WriteLine("Original string: {0}", sHello) Console.WriteLine("Find substring (Instr(1, sHello, 'World')) : {0}", InStr(1, sHello, "Wor ld")) End Sub
End Module
|
Original string: Hello World
Find substring (Instr(1, sHello, 'World')) : 7
2.38.21.LCase: change string to lower case
|
Module Tester Public Sub Main() Dim sHello As String = "Hello World" Console.WriteLine("Original string: {0}", sHello) Console.WriteLine("Lowercase (LCase(sHello)) : {0}", LCase(sHello)) End Sub
End Module
|
Original string: Hello World
Lowercase (LCase(sHello)) : hello world
2.38.22.UCase: change string to upper case
|
Module Tester Public Sub Main() Dim sHello As String = "Hello World" Console.WriteLine("Original string: {0}", sHello) Console.WriteLine("Uppercase (UCase(sHello)) : {0}", UCase(sHello)) End Sub
End Module
|
Original string: Hello World
Uppercase (UCase(sHello)) : HELLO WORLD
2.38.23.Change string case using the English-United States and Turkish-Turkey cultures and then compare
|
' Sample for String.ToUpper(CultureInfo) Imports System Imports System.Globalization Imports Microsoft.VisualBasic
Class Sample
Public Shared Sub Main() Dim str1 As [String] = "idea" Dim str2, str3 As [String]
Console.WriteLine("str2 = Upper case copy of str1 using English-United States culture.") str2 = str1.ToUpper(New CultureInfo("en-US", False))
Console.WriteLine("str3 = Upper case copy of str1 using Turkish-Turkey culture.") str3 = str1.ToUpper(New CultureInfo("tr-TR", False))
Console.WriteLine("str2 is {0} to str3.", IIf(0 = [String].CompareOrdinal(str2, str3), "equal", "not equal")) DeCode(str1) DeCode(str2) DeCode(str3) End Sub
Public Shared Sub DeCode( s As [String]) Dim c As Char For Each c In s Console.Write("{0:x4} ", AscW(c)) Next c Console.WriteLine() End Sub End Class
|
2.38.24.Determines whether a string is normalized to various normalization forms(String.Normalize and the String.IsNormalized method)
|
Imports System Imports System.Text Imports Microsoft.VisualBasic
Class Sample Public Shared Sub Main() Dim s1 = New [String](New Char() {ChrW(&H0063), ChrW(&H0301), ChrW(&H0327), ChrW(&H00BE)}) Dim s2 As String = Nothing
Try Show("s1", s1) Console.WriteLine("A1) Is s1 normalized to the default form (Form C)?: {0}", s1.IsNormalized()) Console.WriteLine("A2) Is s1 normalized to Form C?: {0}", s1.IsNormalized(NormalizationForm.FormC)) Console.WriteLine("A3) Is s1 normalized to Form D?: {0}", s1.IsNormalized(NormalizationForm.FormD)) Console.WriteLine("A4) Is s1 normalized to Form KC?: {0}", s1.IsNormalized(NormalizationForm.FormKC)) Console.WriteLine("A5) Is s1 normalized to Form KD?: {0}", s1.IsNormalized(NormalizationForm.FormKD))
Catch e As Exception Console.WriteLine(e.Message) End Try End Sub Private Shared Sub Show(title As String, s As String) Console.Write("Characters in string {0} = ", title) Dim x As Char For Each x In s.ToCharArray() Console.Write("{0:X4} ", AscW(x)) Next x Console.WriteLine() End Sub End Class
|
2.39.1.Is a string a numeric value
|
Class Tester Shared Sub Main() Dim userInput As String userInput = " asdf "
Console.WriteLine(IsNumeric(userInput) = False) End Sub
End Class
|
2.39.2.Convert string to value
|
Class Tester Shared Sub Main() Dim userInput As String userInput = "4"
Console.WriteLine(Val(userInput)) End Sub
End Class
|
2.39.3.Interpret numeric strings as a hexadecimal value and convert it to an unsigned long integer.
|
Module Example Public Sub Main() Dim hexStrings() As String = { "8", "0FFFFFFF", "F00", "00A", "D"} For Each hexString As String In hexStrings Try Dim number As UInteger = Convert.ToUInt32(hexString, 16) Console.WriteLine("{0,18:N0}", number) Catch e As FormatException Console.WriteLine("{0,18}", "Bad Format") Catch e As OverflowException Console.WriteLine("{0,18}", "Numeric Overflow") Catch e As ArgumentException Console.WriteLine("{0,18}", "Invalid in Base 16") End Try Next End Sub End Module
|
2.40.1.Demonstrating StringBuilder class constructors
|
Imports System.Text
Module Tester
Sub Main() Dim buffer1, buffer2, buffer3 As StringBuilder
buffer1 = New StringBuilder() buffer2 = New StringBuilder(10) buffer3 = New StringBuilder("hello")
Console.WriteLine(buffer1.ToString())
Console.WriteLine(buffer2.ToString())
Console.WriteLine(buffer3.ToString())
End Sub ' Main
End Module
|
2.40.2.StringBuilder: Insert string, Append and Replace
|
Public Class Tester Public Shared Sub Main Dim result As New System.Text.StringBuilder("AA ") result.Append("CCC. ") result.Append("AAA").Append("rrr ").Append("eee")
result.Insert(3, "note to stop ") result.Replace("CC", "rr") result.Insert(0, vbNewLine)
Console.WriteLine(result.ToString()) End Sub
End Class
|
AA note to stop rrC. AAArrr eee
2.40.3.Append Char to StringBuilder
|
Option Strict On
Imports System.Text
Public Module modMain Public Sub Main() Dim chars() As Char = {"T"c,"h"c,"i"c,"s"c," "c,"i"c,"s"c, _ " "c,"a"c,"n"c," "c,"a"c,"r"c,"r"c,"a"c, _ "y"c," "c,"o"c,"f"c," "c,"C"c,"h"c, _ "a"c,"r"c,"s"c} Dim convertedChars As New StringBuilder
For Each ch As Char in chars convertedChars.Append(ch) Next
Dim displayString As String = convertedChars.ToString() Console.WriteLine(displayString) End Sub End Module
|
This is an array of Chars
2.40.4.Demonstrating StringBuilder Append methods
|
Imports System.Text Imports System.Windows.Forms
Module modBuilderAppend
Sub Main() Dim objectValue As Object = "hello" Dim stringValue As String = "good bye" Dim characterArray As Char() = {"a"c, "b"c, "c"c, "d"c, "e"c, "f"c}
Dim booleanValue As Boolean = True Dim characterValue As Char = "Z"c Dim integerValue As Integer = 7 Dim longValue As Long = 1000000 Dim singleValue As Single = 2.5 Dim doubleValue As Double = 33.333 Dim buffer As StringBuilder = New StringBuilder()
buffer.Append(objectValue) buffer.Append(" ") buffer.Append(stringValue) buffer.Append(" ") buffer.Append(characterArray) buffer.Append(" ") buffer.Append(characterArray, 0, 3) buffer.Append(" ") buffer.Append(booleanValue) buffer.Append(" ") buffer.Append(characterValue) buffer.Append(" ") buffer.Append(integerValue) buffer.Append(" ") buffer.Append(longValue) buffer.Append(" ") buffer.Append(singleValue) buffer.Append(" ") buffer.Append(doubleValue)
Console.WriteLine("buffer = " & buffer.ToString()) End Sub
End Module
|
buffer = hello good bye abcdef abc True Z 7 1000000 2.5 33.333
2.40.5.StringBuilder AppendFormat
|
Imports System.Text
Class Tester Public Shared Sub Main( ) Dim s1 As String = "One,Two,Three Liberty Associates, Inc."
Const Space As Char = " "c Const Comma As Char = ","c
Dim delimiters( ) As Char = {Space, Comma}
Dim output As New StringBuilder( ) Dim ctr As Integer = 0
Dim resultArray As String( ) = s1.Split(delimiters)
Dim subString As String For Each subString In resultArray ctr = ctr + 1 output.AppendFormat("{0} : {1}" & Environment.NewLine, ctr, subString) Next subString Console.WriteLine(output) End Sub End Class
|
Your balance as of May 16, 2002 is $ 19,950.40
2.40.6.StringBuilder.AppendFormat: {0:D} is ${1: #,###.00}
|
Imports System
public class Test public Shared Sub Main Dim objSB As New Text.StringBuilder
objSB.AppendFormat("Your balance as of {0:D} is ${1: #,###.00}", _ #5/16/2002#, 19950.4) Console.WriteLine(objSB.ToString)
End Sub End class
|
Your balance as of May 16, 2002 is $ 19,950.40
|
Imports System Imports System.Text
Class Sample Public Shared Sub Main() Dim str As String = "The quick br!wn d#g jumps #ver the lazy cat." Dim sb As New StringBuilder(str)
Console.WriteLine("{0}", sb.ToString())
sb.Replace("#"c, "!"c, 15, 29) ' Some '#' -> '!' Console.WriteLine("{0}", sb.ToString()) sb.Replace("!"c, "o"c) ' All '!' -> 'o' Console.WriteLine("{0}", sb.ToString()) sb.Replace("cat", "dog") ' All "cat" -> "dog" Console.WriteLine("{0}", sb.ToString()) sb.Replace("dog", "fox", 15, 20) ' Some "dog" -> "fox" Console.WriteLine("Final value:") Console.WriteLine("{0}", sb.ToString()) End Sub 'Main
End Class
|
2.40.8.Insert method of StringBuilder
|
Imports System Imports System.Text
Class Sample Private Shared sb As StringBuilder
Public Shared Sub Main() Dim xyz As String = "xyz" Dim abc As Char() = {"a"c, "b"c, "c"c} Dim star As Char = "*"c Dim obj As [Object] = 0
Dim xBool As Boolean = True Dim xByte As Byte = 1 Dim xInt16 As Short = 2 Dim xInt32 As Integer = 3 Dim xInt64 As Long = 4 Dim xDecimal As [Decimal] = 5 Dim xSingle As Single = 6.6F Dim xDouble As Double = 7.7
Dim xUInt16 As System.UInt16 = 8 Dim xUInt32 As System.UInt32 = 9 Dim xUInt64 As System.UInt64 = 10 Dim xSByte As System.SByte = - 11 sb = New StringBuilder()
sb.Insert(3, xyz, 2) sb.Insert(3, xyz) sb.Insert(3, star) sb.Insert(3, abc) sb.Insert(3, abc, 1, 2) sb.Insert(3, xBool) sb.Insert(3, obj) sb.Insert(3, xByte) sb.Insert(3, xInt16) sb.Insert(3, xInt32) sb.Insert(3, xInt64) sb.Insert(3, xDecimal) sb.Insert(3, xSingle) sb.Insert(3, xDouble) sb.Insert(3, xUInt16) sb.Insert(3, xUInt32) sb.Insert(3, xUInt64) sb.Insert(3, xSByte)
Console.WriteLine(sb.ToString())
End Sub End Class
|
2.40.9.StringBuilder: Length, Capacity, EnsureCapacity
|
Imports System.Text
Module Tester
Sub Main() Dim i As Integer Dim buffer As StringBuilder = New StringBuilder("Hello, how are you?")
' use Length and Capacity properties Console.WriteLine("buffer = " & buffer.ToString & _ vbCrLf & "Length = " & buffer.Length & vbCrLf & _ "Capacity = " & buffer.Capacity)
buffer.EnsureCapacity(75)
Console.WriteLine("New capacity = " & buffer.Capacity)
' truncate StringBuilder by setting Length property buffer.Length = 10 Console.WriteLine("New Length = " & buffer.Length )
End Sub
End Module
|
buffer = Hello, how are you?
2.40.10.Use StringBuilder Indexer
|
Imports System.Text
Module Tester
Sub Main() Dim i As Integer Dim buffer As StringBuilder = New StringBuilder("Hello, how are you?")
' use StringBuilder Indexer For i = 0 To buffer.Length - 1 Console.WriteLine(buffer(i)) Next
End Sub
End Module
|
2.40.11.Demonstrating methods Insert and Remove of the StringBuilder class
|
Imports System.Text Imports System.Windows.Forms
Module Tester
Sub Main() Dim objectValue As Object = "hello" Dim stringValue As String = "good bye" Dim characterArray As Char() = {"a"c, "b"c, "c"c, "d"c, "e"c, "f"c}
Dim booleanValue As Boolean = True Dim characterValue As Char = "K"c Dim integerValue As Integer = 7 Dim longValue As Long = 12345677890 Dim singleValue As Single = 2.5 Dim doubleValue As Double = 33.333 Dim buffer As StringBuilder = New StringBuilder() Dim output As String
' insert values into buffer buffer.Insert(0, objectValue) buffer.Insert(0, " ") 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, integerValue) buffer.Insert(0, " ") buffer.Insert(0, longValue) buffer.Insert(0, " ") buffer.Insert(0, singleValue) buffer.Insert(0, " ") buffer.Insert(0, doubleValue) buffer.Insert(0, " ")
output = "buffer after inserts:" & vbCrLf & _ buffer.ToString() & vbCrLf & vbCrLf
buffer.Remove(12, 1) ' delete 5 in 2.5 buffer.Remove(2, 4) ' delete 33.3 in 33.333
output &= "buffer after Removes:" & vbCrLf & _ buffer.ToString()
Console.WriteLine(output) End Sub ' Main
End Module
|
33.333 2.5 12345677890 7 K True abcdef good bye hello
33 2. 12345677890 7 K True abcdef good bye hello
2.40.12.Demonstrating method Replace
|
Imports System.Text Imports System.Windows.Forms
Module Tester
Sub Main() Dim builder1 As StringBuilder = New StringBuilder("Happy Birthday")
Dim builder2 As StringBuilder = New StringBuilder("good bye ")
builder1.Replace("H", "G") builder2.Replace("g"c, "G"c, 0, 5)
Console.WriteLine(builder1.ToString() & vbCrLf & _ builder2.ToString())
End Sub ' Main
End Module
|
2.40.13.Use StringBuilder to reverse a string
|
Imports System
public class Test public Shared Sub Main Dim data As String = "abcdefgh"
Dim objSB As New Text.StringBuilder Dim intLength As Integer = Len(data) Dim intChar As Integer Dim chr As Char Dim objTS As TimeSpan Dim dteStart As Date
objSB.Capacity = intLength objSB.Append(data) dteStart = Now()
For intChar = 0 To CInt(objSB.Length / 2 - 1) chr = objSB.Chars(intChar) objSB.Chars(intChar) = objSB.Chars(intLength - intChar - 1) objSB.Chars(intLength - intChar - 1) = chr Next
objTS = Now().Subtract(dteStart) Console.WriteLine(objTS.ToString) Console.WriteLine(objSB.ToString) End Sub End class
|
2.40.14.StringBuilder.ToStrings
|
Imports System
public class Test public Shared Sub Main Dim objSB As New Text.StringBuilder("some text")
Console.WriteLine(objSB.ToString)
End Sub End class
|
2.40.15.Performance difference between String and StringBuilder
|
Imports System.Text public class Test
public Shared Sub Main Const ADD_STRING As String = "1234567890" Dim num_trials As Long = 1000 Dim start_time As DateTime Dim stop_time As DateTime Dim elapsed_time As TimeSpan Dim txt As String Dim string_builder As New StringBuilder
txt = "" start_time = Now For i As Long = 1 To num_trials txt = txt & ADD_STRING Next i stop_time = Now elapsed_time = stop_time.Subtract(start_time) Console.WriteLine(elapsed_time.TotalSeconds.ToString("0.000000"))
txt = "" start_time = Now For i As Long = 1 To num_trials string_builder.Append(ADD_STRING) Next i txt = string_builder.ToString() stop_time = Now elapsed_time = stop_time.Subtract(start_time) Console.WriteLine(elapsed_time.TotalSeconds.ToString("0.000000"))
End Sub
End class
|
2.41.StringReader StringWriter
2.41.1.StringWriter and StringReader
|
Imports System.IO
public class Test public Shared Sub Main Dim string_writer As New StringWriter() string_writer.WriteLine("The quick brown fox") string_writer.WriteLine("jumps over the lazy dog.") Console.WriteLine(string_writer.ToString)
' Use a StringReader to read from the string. Dim string_reader As New StringReader(string_writer.ToString) string_writer.Close() Console.WriteLine(string_reader.ReadLine()) Console.WriteLine(string_reader.ReadToEnd()) string_reader.Close()
End Sub End class
|
2.42.1.Convert string to base64string
|
Public Class Tester Public Shared Sub Main Dim quote As String = "AAAAA" Dim quoteBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(quote) Dim quote64 As String = Convert.ToBase64String(quoteBytes)
Dim byteSet As Byte() = Convert.FromBase64String(quote64) Dim result As String = System.Text.Encoding.UTF8.GetString(byteSet) Console.WriteLine(quote & vbNewLine & quote64 & vbNewLine & result) End Sub
End Class
|
|
Option Strict On
Public Class WrappedType Public Shared Sub Main() Dim intVar As Integer = 100 Dim intType As Type = intVar.GetType() Console.WriteLine(TypeName(intVar) & " = " & intType.FullName)
Dim stringVar As String = "This is a string." Dim stringType As Type = stringVar.GetType() Console.WriteLine(TypeName(stringVar) & " = " & stringType. FullName)
Dim boolVar As Boolean = True Dim boolType As Type = boolVar.GetType() Console.WriteLine(TypeName(boolVar) & " = " & boolType. FullName)
Dim singleVar As Single = 3.1417 Dim singleType As Type = singleVar.GetType() Console.WriteLine(TypeName(singleVar) & " = " & singleType. FullName) End Sub End Class
|
2.43.2.Show .Net Command Types
|
Module Module1
Sub Main() Dim A As Short Dim B As Integer Dim C As Int64 Dim D As Single Dim E As Double Dim F As Char
Console.WriteLine("A: {0} ", A.GetType().FullName) Console.WriteLine("B: {0} ", B.GetType().FullName) Console.WriteLine("C: {0} ", C.GetType().FullName) Console.WriteLine("D: {0} ", D.GetType().FullName) Console.WriteLine("E: {0} ", E.GetType().FullName) Console.WriteLine("F: {0} ", F.GetType().FullName)
End Sub
End Module
|
|
|
|
|
2.43.3.Use Equal to compare Data type
|
Imports System.Collections
public class Test public Shared Sub Main Dim s1 As New String("Hello") Dim s2 As New String("Hello") Console.WriteLine(s1.Equals(s2)) s1 = s2 Console.WriteLine(s1.Equals(s2))
Dim n1 As New Integer() Dim n2 As New Integer() n1 = 10 n2 = 10
Console.WriteLine(n1.Equals(n2)) n1 = 20 Console.WriteLine(n1.Equals(n2)) End Sub End class
|
|
public class Test Public Const MAX_VALUES As Integer = CInt(123.45)
public Shared Sub Main End Sub End class
|
|
Option Strict On
Public Module FixTest Public Sub Main() Dim arr() As Decimal = {12.6d, 12.1d, -12.1d, -12.6d} For Each num As Decimal In arr Console.WriteLine("Fix({0}): {1}", num, Fix(num)) Console.WriteLine("Int({0}): {1}", num, Int(num)) Console.WriteLine() Next End Sub End Module
|
2.44.3.Math.Round with IRR
|
Option Strict On
Public Module modMain Public Sub Main() Dim cashFlow() As Double = {-102450.55, -30967.12, 134.85, 82930.91, _ 121766.18, 90345.58, 125093.16} Dim guess As Double = .15 Console.WriteLine("{0}", Math.Round(IRR(cashFlow, guess)*100,1)) End Sub End Module
|
2.44.4.CInt: convert Hexadecimal in string to int
|
Option Strict On
Public Module modMain Public Sub Main() Dim convertedHex As Integer = CInt("&H75FF") Console.WriteLine(convertedHex) End Sub End Module
|
2.45.1.CLng: convert integer to long
|
Module Tester Public Sub Main() Dim iInteger As Integer = 5280 Dim lLong As Long Dim bytByte As Byte Dim sngSingle As Single Dim dblDouble As Double Dim decDecimal As Decimal
Console.WriteLine("Convert to a Long: {0}", CLng(iInteger) * CLng(iInteger)) End Sub
End Module
|
Convert to a Long: 27878400
2.45.2.CByte: convert to byte
|
Module Tester Public Sub Main() Dim iInteger As Integer = 5280 Dim lLong As Long Dim bytByte As Byte Dim sngSingle As Single Dim dblDouble As Double Dim decDecimal As Decimal
Console.Writeline("Convert to a Byte: {0}", CByte(iInteger)) End Sub
End Module
|
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.
2.45.3.CSng: convert to Single
|
Module Tester Public Sub Main() Dim iInteger As Integer = 5280 Dim lLong As Long Dim bytByte As Byte Dim sngSingle As Single Dim dblDouble As Double Dim decDecimal As Decimal
Console.WriteLine("Convert to a Single: {0}", CSng(iInteger) / 3.4) End Sub
End Module
|
Convert to a Single: 1552.94117647059
2.45.4.CDbl: convert to double
|
Module Tester Public Sub Main() Dim iInteger As Integer = 5280 Dim lLong As Long Dim bytByte As Byte Dim sngSingle As Single Dim dblDouble As Double Dim decDecimal As Decimal
Console.WriteLine("Convert to a Double: {0}", CDbl(iInteger) / 6.123) End Sub
End Module
|
Convert to a Double: 862.322390984811
2.45.5.CDec: convert to decimal
|
Module Tester Public Sub Main() Dim iInteger As Integer = 5280 Dim lLong As Long Dim bytByte As Byte Dim sngSingle As Single Dim dblDouble As Double Dim decDecimal As Decimal
Console.WriteLine("Convert to a Decimal: {0}", CDec(iInteger) / 34) End Sub
End Module
|
Convert to a Decimal: 155.29411764705882352941176471
2.45.6.Call Int64TryParse(String, NumberStyles, IFormatProvider, Int32)
|
Imports System.Globalization
Module StringParsing Public Sub Main() Dim numericString As String Dim styles As NumberStyles
numericString = "106779" styles = NumberStyles.Integer CallTryParse(numericString, styles)
numericString = "-30677" styles = NumberStyles.None CallTryParse(numericString, styles)
styles = NumberStyles.AllowLeadingSign CallTryParse(numericString, styles)
numericString = "301677-" CallTryParse(numericString, styles)
styles = styles Or NumberStyles.AllowTrailingSign CallTryParse(numericString, styles)
numericString = "$10634" styles = NumberStyles.Integer CallTryParse(numericString, styles)
styles = NumberStyles.Integer Or NumberStyles.AllowCurrencySymbol CallTryParse(numericString, styles)
numericString = "10345.00" styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint CallTryParse(numericString, styles)
numericString = "10345.72" styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint CallTryParse(numericString, styles)
numericString = "22,593" styles = NumberStyles.Integer Or NumberStyles.AllowThousands CallTryParse(numericString, styles)
numericString = "12E-01" styles = NumberStyles.Integer Or NumberStyles.AllowExponent CallTryParse(numericString, styles)
numericString = "12E03" CallTryParse(numericString, styles)
numericString = "80c1" CallTryParse(numericString, NumberStyles.HexNumber)
numericString = "0x80C1" CallTryParse(numericString, NumberStyles.HexNumber)
End Sub
Private Sub CallTryParse(stringToConvert As String, styles AS NumberStyles) Dim number As Long Dim provider As CultureInfo If CBool(styles And NumberStyles.AllowCurrencySymbol) Then provider = CultureInfo.CurrentCulture Else provider = New CultureInfo("en-US") End If
Dim result As Boolean = Int64.TryParse(stringToConvert, styles,provider, number) If result Then Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number) Else Console.WriteLine("Attempted conversion of '{0}' failed.", Convert.ToString(stringToConvert)) End If End Sub End Module
|
2.45.7.Convert a string into a 64-bit signed integer value using the Int64.Parse(String) method
|
Module MainClass Public Sub Main() Convert(" 1") End Sub
Private Sub Convert(value As String) Try Dim number As Long = Int64.Parse(value) Console.WriteLine("Converted '{0}' to {1}.", value, number) Catch e As FormatException Console.WriteLine("Unable to convert '{0}'.", value) Catch e As OverflowException Console.WriteLine("'{0}' is out of range.", value) End Try End Sub End Module
|
2.45.8.Convert.ToBase64CharArray() and Convert.FromBase64CharArray methods
|
Imports System
Class Sample Public Shared Sub Main() Dim byteArray1(255) As Byte Dim byteArray2(255) As Byte Dim charArray(351) As Char Dim charArrayLength As Integer
Dim x As Integer For x = 0 To byteArray1.Length - 1 byteArray1(x) = CByte(x) Console.Write("{0:X2} ", byteArray1(x)) Next x
charArrayLength = Convert.ToBase64CharArray( _ byteArray1, 0, byteArray1.Length, _ charArray, 0, _ Base64FormattingOptions.InsertLineBreaks) Console.Write(charArrayLength) Console.WriteLine(New [String](charArray))
byteArray2 = Convert.FromBase64CharArray(charArray, 0, charArrayLength)
End Sub
End Class
|
2.45.9.Converts the bit patterns of UInt32 values to Byte arrays with the GetBytes method.
|
Imports System Imports Microsoft.VisualBasic
Module GetBytesUInt32Demo Sub GetBytesUInt32( argument As UInt32 ) Dim byteArray As Byte( ) = BitConverter.GetBytes( argument ) Console.WriteLine( BitConverter.ToString( byteArray ) ) End Sub
Sub Main( ) GetBytesUInt32( Convert.ToUInt32( 15 ) ) GetBytesUInt32( Convert.ToUInt32( &H100000 ) ) GetBytesUInt32( Convert.ToUInt32( Int32.MaxValue ) ) End Sub End Module
|
2.45.10.Convert.ToString( non-numeric types, IFormatProvider ).
|
Imports System Imports System.Globalization Imports Microsoft.VisualBasic
Public Class DummyProvider Implements IFormatProvider
Public Function GetFormat( argType As Type ) As Object _ Implements IFormatProvider.GetFormat Console.Write( "{0,-40}", argType.ToString( ) ) Return Nothing End Function End Class
Module MainClass Sub Main( ) Dim provider As New DummyProvider( ) Dim converted As String
Dim Int32A As Integer = -1111111 Dim DoubleA As Double = 6.3 Dim ObjDouble As Object = CType( -98765.4321, Object ) Dim DayTimeA As DateTime = new DateTime( 2010, 9, 1, 13, 45, 0 )
Dim BoolA As Boolean = True Dim StringA As String = "Qwerty" Dim CharA As Char = "$"c Dim TSpanA As TimeSpan = New TimeSpan( 0, 18, 0 ) Dim ObjOther As Object = CType( provider, Object )
converted = Convert.ToString( Int32A, provider ) Console.WriteLine( "Int32 {0}", converted )
converted = Convert.ToString( Int32A, provider ) Console.WriteLine( "Int32 {0}", converted ) converted = Convert.ToString( DoubleA, provider ) Console.WriteLine( "Double {0}", converted ) converted = Convert.ToString( ObjDouble, provider ) Console.WriteLine( "Object {0}", converted ) converted = Convert.ToString( DayTimeA, provider ) Console.WriteLine( "DateTime {0}", converted )
converted = Convert.ToString( BoolA, provider ) Console.WriteLine( "Boolean {0}", converted ) converted = Convert.ToString( StringA, provider ) Console.WriteLine( "String {0}", converted ) converted = Convert.ToString( CharA, provider ) Console.WriteLine( "Char {0}", converted ) converted = Convert.ToString( TSpanA, provider ) Console.WriteLine( "TimeSpan {0}", converted ) converted = Convert.ToString( ObjOther, provider ) Console.WriteLine( "Object {0}", converted )
End Sub End Module
|
2.45.11.Create a hexadecimal value out of range of the UInt64 type and Convert it back to a number.
|
Module Example Public Sub Main()
Dim value As String = Convert.ToString(Long.MinValue, 16) Try Dim number As UInt64 = Convert.ToUInt64(value, 16) Console.WriteLine("0x{0} converts to {1}.", value, number) Catch e As OverflowException Console.WriteLine("Unable to convert '0x{0}' to an unsigned long integer.",value) End Try End Sub End Module
|
|
' 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
Dim matrixA(,) As Double = { _ {4, 5, 6}, _ {7, 8, 9}, _ {3, 2, 1}} Console.WriteLine(MatrixHelper.MakeDisplayable(matrixA))
End Sub End Class
Module MatrixHelper Public Function MakeDisplayable(ByVal sourceMatrix(,) As Double) As String ' ----- Prepare a multi-line string that shows the contents ' of a matrix, a 2D array. Dim rows As Integer Dim cols As Integer Dim eachRow As Integer Dim eachCol As Integer Dim result As New System.Text.StringBuilder
' ----- Process all rows of the matrix, generating one ' output line per row. rows = UBound(sourceMatrix, 1) + 1 cols = UBound(sourceMatrix, 2) + 1 For eachRow = 0 To rows - 1 ' ----- Process each column of the matrix on a single ' row, separating values by commas. If (eachRow > 0) Then result.AppendLine() For eachCol = 0 To cols - 1 ' ----- Add a single matrix element to the output. If (eachCol > 0) Then result.Append(",") result.Append(sourceMatrix(eachRow, eachCol).ToString) Next eachCol Next eachRow
' ----- Finished. Return result.ToString End Function
Public Function MakeDisplayable(ByVal sourceArray() As Double) As String ' ----- Present an array as multiple lines of output. Dim result As New System.Text.StringBuilder Dim scanValue As Double
For Each scanValue In sourceArray result.AppendLine(scanValue.ToString) Next scanValue
Return result.ToString End Function
Public Function Inverse(ByVal sourceMatrix(,) As Double) As Double(,) ' ----- Build a new matrix that is the mathematical inverse ' of the supplied matrix. Multiplying a matrix and its ' inverse together will give the identity matrix. Dim eachCol As Integer Dim eachRow As Integer Dim rowsAndCols As Integer
' ----- Determine the size of each dimension of the matrix. ' Only square matrices can be inverted. If (UBound(sourceMatrix, 1) <> UBound(sourceMatrix, 2)) Then Throw New Exception("Matrix must be square.") End If Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Clone a copy of the matrix (not just a new reference). Dim workMatrix(,) As Double = _ CType(sourceMatrix.Clone, Double(,))
' ----- Variables used for backsolving. Dim destMatrix(rank, rank) As Double Dim rightHandSide(rank) As Double Dim solutions(rank) As Double Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer
' ----- Use LU decomposition to form a triangular matrix. workMatrix = FormLU(workMatrix, rowPivots, colPivots, rowsAndCols)
' ----- Backsolve the triangular matrix to get the inverted ' value for each position in the final matrix. For eachCol = 0 To rank rightHandSide(eachCol) = 1 BackSolve(workMatrix, rightHandSide, solutions, rowPivots, colPivots) For eachRow = 0 To rank destMatrix(eachRow, eachCol) = solutions(eachRow) rightHandSide(eachRow) = 0 Next eachRow Next eachCol
' ----- Return the inverted matrix result. Return destMatrix End Function
Public Function Determinant(ByVal sourceMatrix(,) As Double) As Double ' ----- Calculate the determinant of a matrix. Dim result As Double Dim pivots As Integer Dim count As Integer
' ----- Only calculate the determinants of square matrices. If (UBound(sourceMatrix, 1) <> UBound(sourceMatrix, 2)) Then Throw New Exception( _ "Determinant only calculated for square matrices.") End If Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Make a copy of the matrix so we can work inside of it. Dim workMatrix(rank, rank) As Double Array.Copy(sourceMatrix, workMatrix, sourceMatrix.Length)
' ----- Use LU decomposition to form a triangular matrix. Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer workMatrix = FormLU(workMatrix, rowPivots, colPivots, count)
' ----- Get the product at each of the pivot points. result = 1 For pivots = 0 To rank result *= workMatrix(rowPivots(pivots), colPivots(pivots)) Next pivots
' ----- Determine the sign of the result using LaPlace's formula. result = (-1) ^ count * result Return result End Function
Public Function SimultEq(ByVal sourceEquations(,) As Double, _ ByVal sourceRHS() As Double) As Double() ' ----- Use matrices to solve simultaneous equations. Dim rowsAndCols As Integer
' ----- The matrix must be square and the array size must match. Dim rank As Integer = UBound(sourceEquations, 1) If (UBound(sourceEquations, 2) <> rank) Or _ (UBound(sourceRHS, 1) <> rank) Then Throw New Exception("Size problem for simultaneous equations.") End If
' ----- Create some arrays for doing all of the work. Dim coefficientMatrix(rank, rank) As Double Dim rightHandSide(rank) As Double Dim solutions(rank) As Double Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer
' ----- Make copies of the original matrices so we don't ' mess them up. Array.Copy(sourceEquations, coefficientMatrix, sourceEquations.Length) Array.Copy(sourceRHS, rightHandSide, sourceRHS.Length)
' ----- Use LU decomposition to form a triangular matrix. coefficientMatrix = FormLU(coefficientMatrix, rowPivots, _ colPivots, rowsAndCols)
' ----- Find the unique solution for the upper-triangle. BackSolve(coefficientMatrix, rightHandSide, solutions, _ rowPivots, colPivots)
' ----- Return the simultaneous equations result in an array. Return solutions End Function
Private Function FormLU(ByVal sourceMatrix(,) As Double, _ ByRef rowPivots() As Integer, ByRef colPivots() As Integer, _ ByRef rowsAndCols As Integer) As Double(,) ' ----- Perform an LU (lower and upper) decomposition of a matrix, ' a modified form of Gaussian elimination. Dim eachRow As Integer Dim eachCol As Integer Dim pivot As Integer Dim rowIndex As Integer Dim colIndex As Integer Dim bestRow As Integer Dim bestCol As Integer Dim rowToPivot As Integer Dim colToPivot As Integer Dim maxValue As Double Dim testValue As Double Dim oldMax As Double Const Deps As Double = 0.0000000000000001
' ----- Determine the size of the array. Dim rank As Integer = UBound(sourceMatrix, 1) Dim destMatrix(rank, rank) As Double Dim rowNorm(rank) As Double ReDim rowPivots(rank) ReDim colPivots(rank)
' ----- Make a copy of the array so we don't mess it up. Array.Copy(sourceMatrix, destMatrix, sourceMatrix.Length)
' ----- Initialize row and column pivot arrays. For eachRow = 0 To rank rowPivots(eachRow) = eachRow colPivots(eachRow) = eachRow For eachCol = 0 To rank rowNorm(eachRow) += Math.Abs(destMatrix(eachRow, eachCol)) Next eachCol If (rowNorm(eachRow) = 0) Then Throw New Exception("Cannot invert a singular matrix.") End If Next eachRow
' ----- Use Gauss-Jordan elimination on the matrix rows. For pivot = 0 To rank - 1 maxValue = 0 For eachRow = pivot To rank rowIndex = rowPivots(eachRow) For eachCol = pivot To rank colIndex = colPivots(eachCol) testValue = Math.Abs(destMatrix(rowIndex, colIndex)) _ / rowNorm(rowIndex) If (testValue > maxValue) Then maxValue = testValue bestRow = eachRow bestCol = eachCol End If Next eachCol Next eachRow
' ----- Detect a singular, or very nearly singular, matrix. If (maxValue = 0) Then Throw New Exception("Singular matrix used for LU.") ElseIf (pivot > 1) Then If (maxValue < (Deps * oldMax)) Then Throw New Exception("Non-invertible matrix used for LU.") End If End If oldMax = maxValue
' ----- Swap row pivot values for the best row. If (rowPivots(pivot) <> rowPivots(bestRow)) Then rowsAndCols += 1 Swap(rowPivots(pivot), rowPivots(bestRow)) End If
' ----- Swap column pivot values for the best column. If (colPivots(pivot) <> colPivots(bestCol)) Then rowsAndCols += 1 Swap(colPivots(pivot), colPivots(bestCol)) End If
' ----- Work with the current pivot points. rowToPivot = rowPivots(pivot) colToPivot = colPivots(pivot)
' ----- Modify the remaining rows from the pivot points. For eachRow = (pivot + 1) To rank rowIndex = rowPivots(eachRow) destMatrix(rowIndex, colToPivot) = _ -destMatrix(rowIndex, colToPivot) / _ destMatrix(rowToPivot, colToPivot) For eachCol = (pivot + 1) To rank colIndex = colPivots(eachCol) destMatrix(rowIndex, colIndex) += _ destMatrix(rowIndex, colToPivot) * _ destMatrix(rowToPivot, colIndex) Next eachCol Next eachRow Next pivot
' ----- Detect a non-invertible matrix. If (destMatrix(rowPivots(rank), colPivots(rank)) = 0) Then Throw New Exception("Non-invertible matrix used for LU.") ElseIf (Math.Abs(destMatrix(rowPivots(rank), colPivots(rank))) / _ rowNorm(rowPivots(rank))) < (Deps * oldMax) Then Throw New Exception("Non-invertible matrix used for LU.") End If
' ----- Success. Return the LU triangular matrix. Return destMatrix End Function
Private Sub Swap(ByRef firstValue As Integer, ByRef secondValue As Integer) ' ----- Reverse the values of two reference integers. Dim holdValue As Integer holdValue = firstValue firstValue = secondValue secondValue = holdValue End Sub
Private Sub BackSolve(ByVal sourceMatrix(,) As Double, _ ByVal rightHandSide() As Double, ByVal solutions() As Double, _ ByRef rowPivots() As Integer, ByRef colPivots() As Integer) ' ----- Solve an upper-right-triangle matrix. Dim pivot As Integer Dim rowToPivot As Integer Dim colToPivot As Integer Dim eachRow As Integer Dim eachCol As Integer Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Work through all pivot points. This section builds ' the "B" in the AX=B formula. For pivot = 0 To (rank - 1) colToPivot = colPivots(pivot) For eachRow = (pivot + 1) To rank rowToPivot = rowPivots(eachRow) rightHandSide(rowToPivot) += _ sourceMatrix(rowToPivot, colToPivot) _ * rightHandSide(rowPivots(pivot)) Next eachRow Next pivot
' ----- Now solve for each X using the general formula ' x(i) = (b(i) - summation(a(i,j)x(j)))/a(i,i) For eachRow = rank To 0 Step -1 colToPivot = colPivots(eachRow) rowToPivot = rowPivots(eachRow) solutions(colToPivot) = rightHandSide(rowToPivot) For eachCol = (eachRow + 1) To rank solutions(colToPivot) -= _ sourceMatrix(rowToPivot, colPivots(eachCol)) _ * solutions(colPivots(eachCol)) Next eachCol solutions(colToPivot) /= sourceMatrix(rowToPivot, colToPivot) Next eachRow End Sub End Module
|
|
' 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
Dim matrixA(,) As Double = { _ {1, 3, 3}, _ {2, 4, 3}, _ {1, 3, 4}} Dim matrixB(,) As Double = MatrixHelper.Inverse(matrixA)
Console.WriteLine(MatrixHelper.MakeDisplayable(matrixA) & _ vbNewLine & vbNewLine & "Inverse: " & _ vbNewLine & MatrixHelper.MakeDisplayable(matrixB))
End Sub End Class
Module MatrixHelper Public Function MakeDisplayable(ByVal sourceMatrix(,) As Double) As String ' ----- Prepare a multi-line string that shows the contents ' of a matrix, a 2D array. Dim rows As Integer Dim cols As Integer Dim eachRow As Integer Dim eachCol As Integer Dim result As New System.Text.StringBuilder
' ----- Process all rows of the matrix, generating one ' output line per row. rows = UBound(sourceMatrix, 1) + 1 cols = UBound(sourceMatrix, 2) + 1 For eachRow = 0 To rows - 1 ' ----- Process each column of the matrix on a single ' row, separating values by commas. If (eachRow > 0) Then result.AppendLine() For eachCol = 0 To cols - 1 ' ----- Add a single matrix element to the output. If (eachCol > 0) Then result.Append(",") result.Append(sourceMatrix(eachRow, eachCol).ToString) Next eachCol Next eachRow
' ----- Finished. Return result.ToString End Function
Public Function MakeDisplayable(ByVal sourceArray() As Double) As String ' ----- Present an array as multiple lines of output. Dim result As New System.Text.StringBuilder Dim scanValue As Double
For Each scanValue In sourceArray result.AppendLine(scanValue.ToString) Next scanValue
Return result.ToString End Function
Public Function Inverse(ByVal sourceMatrix(,) As Double) As Double(,) ' ----- Build a new matrix that is the mathematical inverse ' of the supplied matrix. Multiplying a matrix and its ' inverse together will give the identity matrix. Dim eachCol As Integer Dim eachRow As Integer Dim rowsAndCols As Integer
' ----- Determine the size of each dimension of the matrix. ' Only square matrices can be inverted. If (UBound(sourceMatrix, 1) <> UBound(sourceMatrix, 2)) Then Throw New Exception("Matrix must be square.") End If Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Clone a copy of the matrix (not just a new reference). Dim workMatrix(,) As Double = _ CType(sourceMatrix.Clone, Double(,))
' ----- Variables used for backsolving. Dim destMatrix(rank, rank) As Double Dim rightHandSide(rank) As Double Dim solutions(rank) As Double Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer
' ----- Use LU decomposition to form a triangular matrix. workMatrix = FormLU(workMatrix, rowPivots, colPivots, rowsAndCols)
' ----- Backsolve the triangular matrix to get the inverted ' value for each position in the final matrix. For eachCol = 0 To rank rightHandSide(eachCol) = 1 BackSolve(workMatrix, rightHandSide, solutions, rowPivots, colPivots) For eachRow = 0 To rank destMatrix(eachRow, eachCol) = solutions(eachRow) rightHandSide(eachRow) = 0 Next eachRow Next eachCol
' ----- Return the inverted matrix result. Return destMatrix End Function
Public Function Determinant(ByVal sourceMatrix(,) As Double) As Double ' ----- Calculate the determinant of a matrix. Dim result As Double Dim pivots As Integer Dim count As Integer
' ----- Only calculate the determinants of square matrices. If (UBound(sourceMatrix, 1) <> UBound(sourceMatrix, 2)) Then Throw New Exception( _ "Determinant only calculated for square matrices.") End If Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Make a copy of the matrix so we can work inside of it. Dim workMatrix(rank, rank) As Double Array.Copy(sourceMatrix, workMatrix, sourceMatrix.Length)
' ----- Use LU decomposition to form a triangular matrix. Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer workMatrix = FormLU(workMatrix, rowPivots, colPivots, count)
' ----- Get the product at each of the pivot points. result = 1 For pivots = 0 To rank result *= workMatrix(rowPivots(pivots), colPivots(pivots)) Next pivots
' ----- Determine the sign of the result using LaPlace's formula. result = (-1) ^ count * result Return result End Function
Public Function SimultEq(ByVal sourceEquations(,) As Double, _ ByVal sourceRHS() As Double) As Double() ' ----- Use matrices to solve simultaneous equations. Dim rowsAndCols As Integer
' ----- The matrix must be square and the array size must match. Dim rank As Integer = UBound(sourceEquations, 1) If (UBound(sourceEquations, 2) <> rank) Or _ (UBound(sourceRHS, 1) <> rank) Then Throw New Exception("Size problem for simultaneous equations.") End If
' ----- Create some arrays for doing all of the work. Dim coefficientMatrix(rank, rank) As Double Dim rightHandSide(rank) As Double Dim solutions(rank) As Double Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer
' ----- Make copies of the original matrices so we don't ' mess them up. Array.Copy(sourceEquations, coefficientMatrix, sourceEquations.Length) Array.Copy(sourceRHS, rightHandSide, sourceRHS.Length)
' ----- Use LU decomposition to form a triangular matrix. coefficientMatrix = FormLU(coefficientMatrix, rowPivots, _ colPivots, rowsAndCols)
' ----- Find the unique solution for the upper-triangle. BackSolve(coefficientMatrix, rightHandSide, solutions, _ rowPivots, colPivots)
' ----- Return the simultaneous equations result in an array. Return solutions End Function
Private Function FormLU(ByVal sourceMatrix(,) As Double, _ ByRef rowPivots() As Integer, ByRef colPivots() As Integer, _ ByRef rowsAndCols As Integer) As Double(,) ' ----- Perform an LU (lower and upper) decomposition of a matrix, ' a modified form of Gaussian elimination. Dim eachRow As Integer Dim eachCol As Integer Dim pivot As Integer Dim rowIndex As Integer Dim colIndex As Integer Dim bestRow As Integer Dim bestCol As Integer Dim rowToPivot As Integer Dim colToPivot As Integer Dim maxValue As Double Dim testValue As Double Dim oldMax As Double Const Deps As Double = 0.0000000000000001
' ----- Determine the size of the array. Dim rank As Integer = UBound(sourceMatrix, 1) Dim destMatrix(rank, rank) As Double Dim rowNorm(rank) As Double ReDim rowPivots(rank) ReDim colPivots(rank)
' ----- Make a copy of the array so we don't mess it up. Array.Copy(sourceMatrix, destMatrix, sourceMatrix.Length)
' ----- Initialize row and column pivot arrays. For eachRow = 0 To rank rowPivots(eachRow) = eachRow colPivots(eachRow) = eachRow For eachCol = 0 To rank rowNorm(eachRow) += Math.Abs(destMatrix(eachRow, eachCol)) Next eachCol If (rowNorm(eachRow) = 0) Then Throw New Exception("Cannot invert a singular matrix.") End If Next eachRow
' ----- Use Gauss-Jordan elimination on the matrix rows. For pivot = 0 To rank - 1 maxValue = 0 For eachRow = pivot To rank rowIndex = rowPivots(eachRow) For eachCol = pivot To rank colIndex = colPivots(eachCol) testValue = Math.Abs(destMatrix(rowIndex, colIndex)) _ / rowNorm(rowIndex) If (testValue > maxValue) Then maxValue = testValue bestRow = eachRow bestCol = eachCol End If Next eachCol Next eachRow
' ----- Detect a singular, or very nearly singular, matrix. If (maxValue = 0) Then Throw New Exception("Singular matrix used for LU.") ElseIf (pivot > 1) Then If (maxValue < (Deps * oldMax)) Then Throw New Exception("Non-invertible matrix used for LU.") End If End If oldMax = maxValue
' ----- Swap row pivot values for the best row. If (rowPivots(pivot) <> rowPivots(bestRow)) Then rowsAndCols += 1 Swap(rowPivots(pivot), rowPivots(bestRow)) End If
' ----- Swap column pivot values for the best column. If (colPivots(pivot) <> colPivots(bestCol)) Then rowsAndCols += 1 Swap(colPivots(pivot), colPivots(bestCol)) End If
' ----- Work with the current pivot points. rowToPivot = rowPivots(pivot) colToPivot = colPivots(pivot)
' ----- Modify the remaining rows from the pivot points. For eachRow = (pivot + 1) To rank rowIndex = rowPivots(eachRow) destMatrix(rowIndex, colToPivot) = _ -destMatrix(rowIndex, colToPivot) / _ destMatrix(rowToPivot, colToPivot) For eachCol = (pivot + 1) To rank colIndex = colPivots(eachCol) destMatrix(rowIndex, colIndex) += _ destMatrix(rowIndex, colToPivot) * _ destMatrix(rowToPivot, colIndex) Next eachCol Next eachRow Next pivot
' ----- Detect a non-invertible matrix. If (destMatrix(rowPivots(rank), colPivots(rank)) = 0) Then Throw New Exception("Non-invertible matrix used for LU.") ElseIf (Math.Abs(destMatrix(rowPivots(rank), colPivots(rank))) / _ rowNorm(rowPivots(rank))) < (Deps * oldMax) Then Throw New Exception("Non-invertible matrix used for LU.") End If
' ----- Success. Return the LU triangular matrix. Return destMatrix End Function
Private Sub Swap(ByRef firstValue As Integer, ByRef secondValue As Integer) ' ----- Reverse the values of two reference integers. Dim holdValue As Integer holdValue = firstValue firstValue = secondValue secondValue = holdValue End Sub
Private Sub BackSolve(ByVal sourceMatrix(,) As Double, _ ByVal rightHandSide() As Double, ByVal solutions() As Double, _ ByRef rowPivots() As Integer, ByRef colPivots() As Integer) ' ----- Solve an upper-right-triangle matrix. Dim pivot As Integer Dim rowToPivot As Integer Dim colToPivot As Integer Dim eachRow As Integer Dim eachCol As Integer Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Work through all pivot points. This section builds ' the "B" in the AX=B formula. For pivot = 0 To (rank - 1) colToPivot = colPivots(pivot) For eachRow = (pivot + 1) To rank rowToPivot = rowPivots(eachRow) rightHandSide(rowToPivot) += _ sourceMatrix(rowToPivot, colToPivot) _ * rightHandSide(rowPivots(pivot)) Next eachRow Next pivot
' ----- Now solve for each X using the general formula ' x(i) = (b(i) - summation(a(i,j)x(j)))/a(i,i) For eachRow = rank To 0 Step -1 colToPivot = colPivots(eachRow) rowToPivot = rowPivots(eachRow) solutions(colToPivot) = rightHandSide(rowToPivot) For eachCol = (eachRow + 1) To rank solutions(colToPivot) -= _ sourceMatrix(rowToPivot, colPivots(eachCol)) _ * solutions(colPivots(eachCol)) Next eachCol solutions(colToPivot) /= sourceMatrix(rowToPivot, colToPivot) Next eachRow End Sub End Module
|
2.46.3.Calculate the determinant of an array
|
' 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 Dim matrixA(,) As Double = { _ {1, 2, 3}, _ {5, 4, 6}, _ {9, 7, 8}} Dim determinant As Double = MatrixHelper.Determinant(matrixA)
Console.WriteLine(MatrixHelper.MakeDisplayable(matrixA) & _ vbNewLine & vbNewLine & "Determinant: " & _ determinant.ToString) End Sub End Class
Module MatrixHelper Public Function MakeDisplayable(ByVal sourceMatrix(,) As Double) As String ' ----- Prepare a multi-line string that shows the contents ' of a matrix, a 2D array. Dim rows As Integer Dim cols As Integer Dim eachRow As Integer Dim eachCol As Integer Dim result As New System.Text.StringBuilder
' ----- Process all rows of the matrix, generating one ' output line per row. rows = UBound(sourceMatrix, 1) + 1 cols = UBound(sourceMatrix, 2) + 1 For eachRow = 0 To rows - 1 ' ----- Process each column of the matrix on a single ' row, separating values by commas. If (eachRow > 0) Then result.AppendLine() For eachCol = 0 To cols - 1 ' ----- Add a single matrix element to the output. If (eachCol > 0) Then result.Append(",") result.Append(sourceMatrix(eachRow, eachCol).ToString) Next eachCol Next eachRow
' ----- Finished. Return result.ToString End Function
Public Function MakeDisplayable(ByVal sourceArray() As Double) As String ' ----- Present an array as multiple lines of output. Dim result As New System.Text.StringBuilder Dim scanValue As Double
For Each scanValue In sourceArray result.AppendLine(scanValue.ToString) Next scanValue
Return result.ToString End Function
Public Function Inverse(ByVal sourceMatrix(,) As Double) As Double(,) ' ----- Build a new matrix that is the mathematical inverse ' of the supplied matrix. Multiplying a matrix and its ' inverse together will give the identity matrix. Dim eachCol As Integer Dim eachRow As Integer Dim rowsAndCols As Integer
' ----- Determine the size of each dimension of the matrix. ' Only square matrices can be inverted. If (UBound(sourceMatrix, 1) <> UBound(sourceMatrix, 2)) Then Throw New Exception("Matrix must be square.") End If Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Clone a copy of the matrix (not just a new reference). Dim workMatrix(,) As Double = _ CType(sourceMatrix.Clone, Double(,))
' ----- Variables used for backsolving. Dim destMatrix(rank, rank) As Double Dim rightHandSide(rank) As Double Dim solutions(rank) As Double Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer
' ----- Use LU decomposition to form a triangular matrix. workMatrix = FormLU(workMatrix, rowPivots, colPivots, rowsAndCols)
' ----- Backsolve the triangular matrix to get the inverted ' value for each position in the final matrix. For eachCol = 0 To rank rightHandSide(eachCol) = 1 BackSolve(workMatrix, rightHandSide, solutions, rowPivots, colPivots) For eachRow = 0 To rank destMatrix(eachRow, eachCol) = solutions(eachRow) rightHandSide(eachRow) = 0 Next eachRow Next eachCol
' ----- Return the inverted matrix result. Return destMatrix End Function
Public Function Determinant(ByVal sourceMatrix(,) As Double) As Double ' ----- Calculate the determinant of a matrix. Dim result As Double Dim pivots As Integer Dim count As Integer
' ----- Only calculate the determinants of square matrices. If (UBound(sourceMatrix, 1) <> UBound(sourceMatrix, 2)) Then Throw New Exception( _ "Determinant only calculated for square matrices.") End If Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Make a copy of the matrix so we can work inside of it. Dim workMatrix(rank, rank) As Double Array.Copy(sourceMatrix, workMatrix, sourceMatrix.Length)
' ----- Use LU decomposition to form a triangular matrix. Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer workMatrix = FormLU(workMatrix, rowPivots, colPivots, count)
' ----- Get the product at each of the pivot points. result = 1 For pivots = 0 To rank result *= workMatrix(rowPivots(pivots), colPivots(pivots)) Next pivots
' ----- Determine the sign of the result using LaPlace's formula. result = (-1) ^ count * result Return result End Function
Public Function SimultEq(ByVal sourceEquations(,) As Double, _ ByVal sourceRHS() As Double) As Double() ' ----- Use matrices to solve simultaneous equations. Dim rowsAndCols As Integer
' ----- The matrix must be square and the array size must match. Dim rank As Integer = UBound(sourceEquations, 1) If (UBound(sourceEquations, 2) <> rank) Or _ (UBound(sourceRHS, 1) <> rank) Then Throw New Exception("Size problem for simultaneous equations.") End If
' ----- Create some arrays for doing all of the work. Dim coefficientMatrix(rank, rank) As Double Dim rightHandSide(rank) As Double Dim solutions(rank) As Double Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer
' ----- Make copies of the original matrices so we don't ' mess them up. Array.Copy(sourceEquations, coefficientMatrix, sourceEquations.Length) Array.Copy(sourceRHS, rightHandSide, sourceRHS.Length)
' ----- Use LU decomposition to form a triangular matrix. coefficientMatrix = FormLU(coefficientMatrix, rowPivots, _ colPivots, rowsAndCols)
' ----- Find the unique solution for the upper-triangle. BackSolve(coefficientMatrix, rightHandSide, solutions, _ rowPivots, colPivots)
' ----- Return the simultaneous equations result in an array. Return solutions End Function
Private Function FormLU(ByVal sourceMatrix(,) As Double, _ ByRef rowPivots() As Integer, ByRef colPivots() As Integer, _ ByRef rowsAndCols As Integer) As Double(,) ' ----- Perform an LU (lower and upper) decomposition of a matrix, ' a modified form of Gaussian elimination. Dim eachRow As Integer Dim eachCol As Integer Dim pivot As Integer Dim rowIndex As Integer Dim colIndex As Integer Dim bestRow As Integer Dim bestCol As Integer Dim rowToPivot As Integer Dim colToPivot As Integer Dim maxValue As Double Dim testValue As Double Dim oldMax As Double Const Deps As Double = 0.0000000000000001
' ----- Determine the size of the array. Dim rank As Integer = UBound(sourceMatrix, 1) Dim destMatrix(rank, rank) As Double Dim rowNorm(rank) As Double ReDim rowPivots(rank) ReDim colPivots(rank)
' ----- Make a copy of the array so we don't mess it up. Array.Copy(sourceMatrix, destMatrix, sourceMatrix.Length)
' ----- Initialize row and column pivot arrays. For eachRow = 0 To rank rowPivots(eachRow) = eachRow colPivots(eachRow) = eachRow For eachCol = 0 To rank rowNorm(eachRow) += Math.Abs(destMatrix(eachRow, eachCol)) Next eachCol If (rowNorm(eachRow) = 0) Then Throw New Exception("Cannot invert a singular matrix.") End If Next eachRow
' ----- Use Gauss-Jordan elimination on the matrix rows. For pivot = 0 To rank - 1 maxValue = 0 For eachRow = pivot To rank rowIndex = rowPivots(eachRow) For eachCol = pivot To rank colIndex = colPivots(eachCol) testValue = Math.Abs(destMatrix(rowIndex, colIndex)) _ / rowNorm(rowIndex) If (testValue > maxValue) Then maxValue = testValue bestRow = eachRow bestCol = eachCol End If Next eachCol Next eachRow
' ----- Detect a singular, or very nearly singular, matrix. If (maxValue = 0) Then Throw New Exception("Singular matrix used for LU.") ElseIf (pivot > 1) Then If (maxValue < (Deps * oldMax)) Then Throw New Exception("Non-invertible matrix used for LU.") End If End If oldMax = maxValue
' ----- Swap row pivot values for the best row. If (rowPivots(pivot) <> rowPivots(bestRow)) Then rowsAndCols += 1 Swap(rowPivots(pivot), rowPivots(bestRow)) End If
' ----- Swap column pivot values for the best column. If (colPivots(pivot) <> colPivots(bestCol)) Then rowsAndCols += 1 Swap(colPivots(pivot), colPivots(bestCol)) End If
' ----- Work with the current pivot points. rowToPivot = rowPivots(pivot) colToPivot = colPivots(pivot)
' ----- Modify the remaining rows from the pivot points. For eachRow = (pivot + 1) To rank rowIndex = rowPivots(eachRow) destMatrix(rowIndex, colToPivot) = _ -destMatrix(rowIndex, colToPivot) / _ destMatrix(rowToPivot, colToPivot) For eachCol = (pivot + 1) To rank colIndex = colPivots(eachCol) destMatrix(rowIndex, colIndex) += _ destMatrix(rowIndex, colToPivot) * _ destMatrix(rowToPivot, colIndex) Next eachCol Next eachRow Next pivot
' ----- Detect a non-invertible matrix. If (destMatrix(rowPivots(rank), colPivots(rank)) = 0) Then Throw New Exception("Non-invertible matrix used for LU.") ElseIf (Math.Abs(destMatrix(rowPivots(rank), colPivots(rank))) / _ rowNorm(rowPivots(rank))) < (Deps * oldMax) Then Throw New Exception("Non-invertible matrix used for LU.") End If
' ----- Success. Return the LU triangular matrix. Return destMatrix End Function
Private Sub Swap(ByRef firstValue As Integer, ByRef secondValue As Integer) ' ----- Reverse the values of two reference integers. Dim holdValue As Integer holdValue = firstValue firstValue = secondValue secondValue = holdValue End Sub
Private Sub BackSolve(ByVal sourceMatrix(,) As Double, _ ByVal rightHandSide() As Double, ByVal solutions() As Double, _ ByRef rowPivots() As Integer, ByRef colPivots() As Integer) ' ----- Solve an upper-right-triangle matrix. Dim pivot As Integer Dim rowToPivot As Integer Dim colToPivot As Integer Dim eachRow As Integer Dim eachCol As Integer Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Work through all pivot points. This section builds ' the "B" in the AX=B formula. For pivot = 0 To (rank - 1) colToPivot = colPivots(pivot) For eachRow = (pivot + 1) To rank rowToPivot = rowPivots(eachRow) rightHandSide(rowToPivot) += _ sourceMatrix(rowToPivot, colToPivot) _ * rightHandSide(rowPivots(pivot)) Next eachRow Next pivot
' ----- Now solve for each X using the general formula ' x(i) = (b(i) - summation(a(i,j)x(j)))/a(i,i) For eachRow = rank To 0 Step -1 colToPivot = colPivots(eachRow) rowToPivot = rowPivots(eachRow) solutions(colToPivot) = rightHandSide(rowToPivot) For eachCol = (eachRow + 1) To rank solutions(colToPivot) -= _ sourceMatrix(rowToPivot, colPivots(eachCol)) _ * solutions(colPivots(eachCol)) Next eachCol solutions(colToPivot) /= sourceMatrix(rowToPivot, colToPivot) Next eachRow End Sub End Module
|
2.46.4.Solve equations using matrices
|
' 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 Dim matrixA(,) As Double = { _ {1, 1, 1, 1}, _ {1, 5, 10, 25}, _ {0, 5, 10, 0}, _ {0, 0, 10, 25}} Dim arrayB() As Double = {18, 223, 70, 200} Dim arrayC() As Double = MatrixHelper.SimultEq(matrixA, arrayB)
Console.WriteLine(MatrixHelper.MakeDisplayable(matrixA) & _ vbNewLine & vbNewLine & MatrixHelper.MakeDisplayable(arrayB) & _ vbNewLine & vbNewLine & "Simultaneous Equations Solution:" & _ vbNewLine & MatrixHelper.MakeDisplayable(arrayC)) End Sub End Class
Module MatrixHelper Public Function MakeDisplayable(ByVal sourceMatrix(,) As Double) As String ' ----- Prepare a multi-line string that shows the contents ' of a matrix, a 2D array. Dim rows As Integer Dim cols As Integer Dim eachRow As Integer Dim eachCol As Integer Dim result As New System.Text.StringBuilder
' ----- Process all rows of the matrix, generating one ' output line per row. rows = UBound(sourceMatrix, 1) + 1 cols = UBound(sourceMatrix, 2) + 1 For eachRow = 0 To rows - 1 ' ----- Process each column of the matrix on a single ' row, separating values by commas. If (eachRow > 0) Then result.AppendLine() For eachCol = 0 To cols - 1 ' ----- Add a single matrix element to the output. If (eachCol > 0) Then result.Append(",") result.Append(sourceMatrix(eachRow, eachCol).ToString) Next eachCol Next eachRow
' ----- Finished. Return result.ToString End Function
Public Function MakeDisplayable(ByVal sourceArray() As Double) As String ' ----- Present an array as multiple lines of output. Dim result As New System.Text.StringBuilder Dim scanValue As Double
For Each scanValue In sourceArray result.AppendLine(scanValue.ToString) Next scanValue
Return result.ToString End Function
Public Function Inverse(ByVal sourceMatrix(,) As Double) As Double(,) ' ----- Build a new matrix that is the mathematical inverse ' of the supplied matrix. Multiplying a matrix and its ' inverse together will give the identity matrix. Dim eachCol As Integer Dim eachRow As Integer Dim rowsAndCols As Integer
' ----- Determine the size of each dimension of the matrix. ' Only square matrices can be inverted. If (UBound(sourceMatrix, 1) <> UBound(sourceMatrix, 2)) Then Throw New Exception("Matrix must be square.") End If Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Clone a copy of the matrix (not just a new reference). Dim workMatrix(,) As Double = _ CType(sourceMatrix.Clone, Double(,))
' ----- Variables used for backsolving. Dim destMatrix(rank, rank) As Double Dim rightHandSide(rank) As Double Dim solutions(rank) As Double Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer
' ----- Use LU decomposition to form a triangular matrix. workMatrix = FormLU(workMatrix, rowPivots, colPivots, rowsAndCols)
' ----- Backsolve the triangular matrix to get the inverted ' value for each position in the final matrix. For eachCol = 0 To rank rightHandSide(eachCol) = 1 BackSolve(workMatrix, rightHandSide, solutions, rowPivots, colPivots) For eachRow = 0 To rank destMatrix(eachRow, eachCol) = solutions(eachRow) rightHandSide(eachRow) = 0 Next eachRow Next eachCol
' ----- Return the inverted matrix result. Return destMatrix End Function
Public Function Determinant(ByVal sourceMatrix(,) As Double) As Double ' ----- Calculate the determinant of a matrix. Dim result As Double Dim pivots As Integer Dim count As Integer
' ----- Only calculate the determinants of square matrices. If (UBound(sourceMatrix, 1) <> UBound(sourceMatrix, 2)) Then Throw New Exception( _ "Determinant only calculated for square matrices.") End If Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Make a copy of the matrix so we can work inside of it. Dim workMatrix(rank, rank) As Double Array.Copy(sourceMatrix, workMatrix, sourceMatrix.Length)
' ----- Use LU decomposition to form a triangular matrix. Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer workMatrix = FormLU(workMatrix, rowPivots, colPivots, count)
' ----- Get the product at each of the pivot points. result = 1 For pivots = 0 To rank result *= workMatrix(rowPivots(pivots), colPivots(pivots)) Next pivots
' ----- Determine the sign of the result using LaPlace's formula. result = (-1) ^ count * result Return result End Function
Public Function SimultEq(ByVal sourceEquations(,) As Double, _ ByVal sourceRHS() As Double) As Double() ' ----- Use matrices to solve simultaneous equations. Dim rowsAndCols As Integer
' ----- The matrix must be square and the array size must match. Dim rank As Integer = UBound(sourceEquations, 1) If (UBound(sourceEquations, 2) <> rank) Or _ (UBound(sourceRHS, 1) <> rank) Then Throw New Exception("Size problem for simultaneous equations.") End If
' ----- Create some arrays for doing all of the work. Dim coefficientMatrix(rank, rank) As Double Dim rightHandSide(rank) As Double Dim solutions(rank) As Double Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer
' ----- Make copies of the original matrices so we don't ' mess them up. Array.Copy(sourceEquations, coefficientMatrix, sourceEquations.Length) Array.Copy(sourceRHS, rightHandSide, sourceRHS.Length)
' ----- Use LU decomposition to form a triangular matrix. coefficientMatrix = FormLU(coefficientMatrix, rowPivots, _ colPivots, rowsAndCols)
' ----- Find the unique solution for the upper-triangle. BackSolve(coefficientMatrix, rightHandSide, solutions, _ rowPivots, colPivots)
' ----- Return the simultaneous equations result in an array. Return solutions End Function
Private Function FormLU(ByVal sourceMatrix(,) As Double, _ ByRef rowPivots() As Integer, ByRef colPivots() As Integer, _ ByRef rowsAndCols As Integer) As Double(,) ' ----- Perform an LU (lower and upper) decomposition of a matrix, ' a modified form of Gaussian elimination. Dim eachRow As Integer Dim eachCol As Integer Dim pivot As Integer Dim rowIndex As Integer Dim colIndex As Integer Dim bestRow As Integer Dim bestCol As Integer Dim rowToPivot As Integer Dim colToPivot As Integer Dim maxValue As Double Dim testValue As Double Dim oldMax As Double Const Deps As Double = 0.0000000000000001
' ----- Determine the size of the array. Dim rank As Integer = UBound(sourceMatrix, 1) Dim destMatrix(rank, rank) As Double Dim rowNorm(rank) As Double ReDim rowPivots(rank) ReDim colPivots(rank)
' ----- Make a copy of the array so we don't mess it up. Array.Copy(sourceMatrix, destMatrix, sourceMatrix.Length)
' ----- Initialize row and column pivot arrays. For eachRow = 0 To rank rowPivots(eachRow) = eachRow colPivots(eachRow) = eachRow For eachCol = 0 To rank rowNorm(eachRow) += Math.Abs(destMatrix(eachRow, eachCol)) Next eachCol If (rowNorm(eachRow) = 0) Then Throw New Exception("Cannot invert a singular matrix.") End If Next eachRow
' ----- Use Gauss-Jordan elimination on the matrix rows. For pivot = 0 To rank - 1 maxValue = 0 For eachRow = pivot To rank rowIndex = rowPivots(eachRow) For eachCol = pivot To rank colIndex = colPivots(eachCol) testValue = Math.Abs(destMatrix(rowIndex, colIndex)) _ / rowNorm(rowIndex) If (testValue > maxValue) Then maxValue = testValue bestRow = eachRow bestCol = eachCol End If Next eachCol Next eachRow
' ----- Detect a singular, or very nearly singular, matrix. If (maxValue = 0) Then Throw New Exception("Singular matrix used for LU.") ElseIf (pivot > 1) Then If (maxValue < (Deps * oldMax)) Then Throw New Exception("Non-invertible matrix used for LU.") End If End If oldMax = maxValue
' ----- Swap row pivot values for the best row. If (rowPivots(pivot) <> rowPivots(bestRow)) Then rowsAndCols += 1 Swap(rowPivots(pivot), rowPivots(bestRow)) End If
' ----- Swap column pivot values for the best column. If (colPivots(pivot) <> colPivots(bestCol)) Then rowsAndCols += 1 Swap(colPivots(pivot), colPivots(bestCol)) End If
' ----- Work with the current pivot points. rowToPivot = rowPivots(pivot) colToPivot = colPivots(pivot)
' ----- Modify the remaining rows from the pivot points. For eachRow = (pivot + 1) To rank rowIndex = rowPivots(eachRow) destMatrix(rowIndex, colToPivot) = _ -destMatrix(rowIndex, colToPivot) / _ destMatrix(rowToPivot, colToPivot) For eachCol = (pivot + 1) To rank colIndex = colPivots(eachCol) destMatrix(rowIndex, colIndex) += _ destMatrix(rowIndex, colToPivot) * _ destMatrix(rowToPivot, colIndex) Next eachCol Next eachRow Next pivot
' ----- Detect a non-invertible matrix. If (destMatrix(rowPivots(rank), colPivots(rank)) = 0) Then Throw New Exception("Non-invertible matrix used for LU.") ElseIf (Math.Abs(destMatrix(rowPivots(rank), colPivots(rank))) / _ rowNorm(rowPivots(rank))) < (Deps * oldMax) Then Throw New Exception("Non-invertible matrix used for LU.") End If
' ----- Success. Return the LU triangular matrix. Return destMatrix End Function
Private Sub Swap(ByRef firstValue As Integer, ByRef secondValue As Integer) ' ----- Reverse the values of two reference integers. Dim holdValue As Integer holdValue = firstValue firstValue = secondValue secondValue = holdValue End Sub
Private Sub BackSolve(ByVal sourceMatrix(,) As Double, _ ByVal rightHandSide() As Double, ByVal solutions() As Double, _ ByRef rowPivots() As Integer, ByRef colPivots() As Integer) ' ----- Solve an upper-right-triangle matrix. Dim pivot As Integer Dim rowToPivot As Integer Dim colToPivot As Integer Dim eachRow As Integer Dim eachCol As Integer Dim rank As Integer = UBound(sourceMatrix, 1)
' ----- Work through all pivot points. This section builds ' the "B" in the AX=B formula. For pivot = 0 To (rank - 1) colToPivot = colPivots(pivot) For eachRow = (pivot + 1) To rank rowToPivot = rowPivots(eachRow) rightHandSide(rowToPivot) += _ sourceMatrix(rowToPivot, colToPivot) _ * rightHandSide(rowPivots(pivot)) Next eachRow Next pivot
' ----- Now solve for each X using the general formula ' x(i) = (b(i) - summation(a(i,j)x(j)))/a(i,i) For eachRow = rank To 0 Step -1 colToPivot = colPivots(eachRow) rowToPivot = rowPivots(eachRow) solutions(colToPivot) = rightHandSide(rowToPivot) For eachCol = (eachRow + 1) To rank solutions(colToPivot) -= _ sourceMatrix(rowToPivot, colPivots(eachCol)) _ * solutions(colPivots(eachCol)) Next eachCol solutions(colToPivot) /= sourceMatrix(rowToPivot, colToPivot) Next eachRow End Sub End Module
|
Simultaneous Equations Solution:
|
public class Test public Shared Sub Main Dim wr As WeakReference Dim obj As New Person() wr = New WeakReference(obj) End Sub
End class
Public Class Person Implements IDisposable Private Disposed As Boolean = False
Public Overloads Sub Dispose() Implements IDisposable.Dispose Dispose(True) System.GC.SuppressFinalize(Me) End Sub Protected Overloads Sub Dispose(ByVal disposing As Boolean) Me.Disposed = True End Sub
Protected Overrides Sub finalize() Console.WriteLine("In Person Finalize") MyBase.Finalize() Me.Dispose(False)
End Sub End Class
|
2.48.1.Assigning Nothing to a variable sets it to the default value for its declared type.
|
Module Module1 Public Structure testStruct Public name As String Public number As Short End Structure
Sub Main()
Dim ts As testStruct Dim i As Integer Dim b As Boolean
' The following statement sets ts.name to "" and ts.number to 0. ts = Nothing
' The following statements set i to 0 and b to False. i = Nothing b = Nothing
Console.WriteLine("ts.name: " & ts.name) Console.WriteLine("ts.number: " & ts.number) Console.WriteLine("i: " & i) Console.WriteLine("b: " & b)
End Sub
End Module
|
2.48.2.Nullable(Of T).GetValueOrDefault methods.
|
Imports System
Class Sample Public Shared Sub Main() Dim mySingle As Nullable(Of System.Single) = 12.34F Dim yourSingle As Nullable(Of System.Single) = - 1.0F
Console.WriteLine(mySingle) Console.WriteLine(yourSingle)
yourSingle = mySingle.GetValueOrDefault() Console.WriteLine(mySingle) Console.WriteLine(yourSingle)
mySingle = Nothing yourSingle = mySingle.GetValueOrDefault() Console.WriteLine(mySingle) Console.WriteLine(yourSingle)
mySingle = 12.34F yourSingle = - 1.0F
Console.WriteLine(mySingle) Console.WriteLine(yourSingle)
yourSingle = mySingle.GetValueOrDefault(- 222.22F) Console.WriteLine(mySingle) Console.WriteLine(yourSingle)
mySingle = Nothing yourSingle = mySingle.GetValueOrDefault(- 333.33F) Console.WriteLine(mySingle) Console.WriteLine(yourSingle)
End Sub
End Class
|
2.48.3.If the variable is of a reference type, a value of Nothing is a null value.
|
Module Module1
Sub Main()
Dim testObject As Object testObject = Nothing
Dim tc As New TestClass tc = Nothing End Sub
Class TestClass Public field1 As Integer End Class End Module
|
Wyszukiwarka
Podobne podstrony:
kurs vba Data Type 2kurs vba Language Basics 1 kolumnykurs vba Date Time 5 kolumnykurs vba Statements 4 kolumnykurs vba Operator 3 kolumnyEXCEL 2003 Kurs VBAkurs vba Statements 4kurs vba Date Time 5kurs vba Operator 3KURS ETYKIChoroba hemolityczna p odu na kurszapotrzebowanie ustroju na skladniki odzywcze 12 01 2009 kurs dla pielegniarek (2)kurswady postawy kursostre białaczki 24 11 2008 (kurs)więcej podobnych podstron