Help with String.CopyTo() - vb.net

I am facing a problem with String.CopyTo() method.
I am trying to the copy the value from string to char array using String.CopyTo() method.
Here's my code
Dim strString As String = "Hello World!"
Dim strCopy(12) As Char
strString.CopyTo(0, strCopy, 0, 12)
For Each ch As Char In strCopy
Console.Write(ch)
Next
Can any one point me in the right direction ?
Thanks.
Edit : I get the this error at runtime.
ArgumentOutOfRangeException
Index and count must refer to a location within the string.
Parameter name: sourceIndex

From the documentation you get ArgumentOutOfRangeException when:
sourceIndex, destinationIndex, or count is negative
-or-
count is greater than the length of the substring from startIndex to the end of this instance
-or-
count is greater than the length of the subarray from destinationIndex to the end of destination
The first case isn't true as these values are zero or positive.
So it must be that the count is too great for the destination array. Rather than hard code the length do something like this:
strSource.CopyTo ( 0, destination, 4, strSource.Length );

You should call the ToCharArray() method instead:
Dim strCopy As Char() = strString.ToCharArray()

Related

how to get the specify items in byte() array in VB

I am working on the VB.NET. I have two arrays need to compare and output the remainder of the longer array. I just simplify my question as following code:
Dim array1 As Byte() = {&H01, &H22,&H10,&HBC,&HA2,&H01,&H00,&HA6,&H02,&HBB,&H33,&H11,&HB2,&H01}
Dim array As Byte() = {&H01, &H22,&H10,&HBC,&HA2,&H01,&H00,&HA6,&H02,&HBB,&H33,&H11,&HB2,&H02,&H77,&H44,&HBF}
Dim remainder As Byte()
IF(array1.Length< array2.Length) then
Dim remainderLength = array2.Length- array1.Length
For...
'''array1.Length =14
'''array2.Length =17
'''write the code to sign the last 3 Hex values into new array remainder and output the remainder
Next
the remainder length might be changed to other sizes, 100, 200 or more. I tried the Item()function and IndexOf()function, and didn't get the result. Please help to write the left code. The final result I want remainder = {&H77,&H44,&HBF}
thank you very much for any comments.
The simplest approach would be to use LINQ's Skip extension method.
For Each b As Byte In array.Skip(array1.Length)
Console.Write(b)
Next
Or:
Dim remainder As Byte() = array.Skip(array1.Length).ToArray()
You may also want to consider using the Array.Copy method which allows you to pass the starting index as an argument:
Array.Copy(array, array1.Length, remainder, 0, array.Length - array1.Length)
Or, if all else fails, it's always possible to access each item in the array by index:
For i As Integer = array1.Length to array.Length
Console.Write(array(i))
Next

Check string in an array

I have strings stored in an array and need to check if the 5th character of each string is a number or not. The code I used is:
If Mid(arr(i), 5, 1) = IsNumeric(True) Then
MsgBox("Number")
End If
It is giving an error:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Boolean' is not valid.
You originally tagged your question as vba, but VBA doesn't throw System.InvalidCastException, or any other exception for that matter; vb.net does.
IsNumeric(True) returns True if True is numeric. You want to verify if the string retrieved from the array is numeric; give it the string retrieved from the array as a parameter:
If IsNumeric(Mid(arr(i), 4, 1)) Then
MsgBox("Number")
End If
Your code reads like VB6/VBA though, because of this:
Imports Microsoft.VisualBasic
That namespace contains VB6-like things that you don't need to use at all. The beauty of .net is that everything is an object, so assuming the array is an array of String, you can call the actual String instance methods instead of VB6's Mid function.
Dim theFifthCharacter As String = arr(i).Substring(4, 1)
Or, because you're only interested in 1 character, and a String is itself an IEnumerable(Of Char), you can do this:
Dim theFifthCharacter As Char = arr(i)(4)
Notice the off-by-one - in .net indices start at 0, so if you want the 5th item you'll fetch index 4.
Now, if you want to see if it's numeric, you can try to parse it:
Dim digitValue As Integer
If Int32.TryParse(theFifthCharacter, digitValue) Then
'numeric: digitValue contains the numeric value
Else
'non-numeric: digitValue contains an Integer's default value (0)
End If
Lastly, if you want a message box, use WinForms' MessageBox instead of VB6's MsgBox:
Dim digitValue As Integer
If Int32.TryParse(theFifthCharacter, digitValue) Then
'numeric: digitValue contains the numeric value
MessageBox.Show(string.Format("Number: {0}", digitValue))
Else
'non-numeric: digitValue contains an Integer's default value (0)
MessageBox.Show("Not a number")
End If
A more correct way to do this would be:
If Char.IsDigit(arr(i)(4)) Then
Your syntax is incorrect. It should be:
If IsNumeric(Mid(arr(i), 5, 1)) Then

build an array of integers inside a for next loop vb.net

i got this far ... my data string, "num_str" contains a set of ~10 numbers, each separated by a comma. the last part of the string is a blank entry, so i use '.Trim' to avoid an error
Dim i As Integer
Dim m_data() As String
m_data = num_str.Split(",")
For i = 0 To UBound(m_data)
If m_data(i).Trim.Length > 0 Then
MsgBox(Convert.ToInt32(m_data(i).Trim))
End If
Next i
as you can see from the Msgbox, each of the numbers successfully pass through the loop.
where i am stuck is how to place all of the 'Convert.ToInt32(m_data(i).Trim)' numbers, which are now presumably integers, into an array.
how do i build an array of integers inside the For / Next loop so i can find MAX and MIN and LAST
TIA
You just need to initialize the array with the zero-based indexer. You can deduce it's initial size from the size of the string():
Dim m_data = num_str.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
Dim intArray(m_data.Length) As Int32
For i = 0 To m_data.Length - 1
intArray(i) = Int32.Parse(m_data(i).Trim())
Next i
Note that i've also used the overload of String.Split which removes empty strings.
This way is more concise using the Select LINQ Operator.
Dim arrayOfInts = num_str.
Split({","c},
StringSplitOptions.RemoveEmptyEntries).
Select(Function(v) Int32.Parse(v.Trim()))
Dim minInt = arrayOfInts.Min()
Dim maxint = arrayOfInts.Max()

VB.Net Extract numbers from string function

My request is one that can extract a number somewhat by a search.
Example:
animalsOwned|4 would return an containing "4"
animals|3|2|1|3 would return an array containing "3", "2", "1", "3"
This would make it easier for me during a file stream reader.
Thank you
Dim astring = "ABCDE|1|2|3|4"
Dim numbers = (From s In astring
Where Char.IsDigit(s)
Select Int32.Parse(s)).ToArray()
This LINQ statement should help. It simply checks each character in a string to see if it's a digit. Note that this only applies to single digit numbers. It becomes a bit more complicated if you want "ABC123" to return 123 vs. 1, 2, 3 array.
Try regular expression. It's a powerful tool for simple text parsing.
Imports System.Text.RegularExpressions
Namespace Demo
Class Program
Shared Function Main(ByVal args As String()) As Integer
Dim array As Integer() = ExtractIntegers("animals|3|2|1|3")
For Each i In array
Console.WriteLine(i)
Next
Return 0
End Function
Shared Function ExtractIntegers(ByVal input As String) As Integer()
Dim pattern As String = "animals(\|(?<number>[0-9]+))*"
Dim match As Match = Regex.Match(input, pattern)
Dim list As New List(Of Integer)
If match.Success Then
For Each capture As Capture In match.Groups("number").Captures
list.Add(Integer.Parse(capture.Value))
Next
End If
Return list.ToArray()
End Function
End Class
End Namespace
I haven't programmed VB for awhile but I'll give you some pseudo code:
First, loop through each line of file. Call this variable Line.
Then, take the index of what you're searching for: like Line.indexOf("animalsOwned")
If it returns -1 it isn't there; continue.
Once you find it, add the Index variable to the length of the search string and 1. (Index=Index+1+Len(searchString))
Then, take a substring starting there, and end at the end of the line.
Explode the substring by | characters, then add each into an array.
Return the array.
Sorry that I can't give you much help, but I'm working on an important PHP website right now ;).
You can do a variable.Split("|") and then assign each piece to an array level.
You can do a count on string and with a while or for loop, you can assign the splited sections to array levels. Then you can do a IsNumeric() check for each array level.

SubString function in vb.net throwing Exception

FromIp contains "192.168.1.1". I want to get the last number, but I can't figure out what's wrong here:
Dim str As String
str = FromIP.Text.Substring(FromIP.Text.LastIndexOf("."), FromIP.Text.Length).ToString()
MessageBox.Show(FromIP.Text.Length)
Eduardo has given the correct way of getting the substring - my answer here will just explain why the existing one fails.
String.Substring(int, int) takes a starting position and a count. You're basically saying, "Go from position 9 for 10 characters". The documentation explicitly states it will throw:
ArgumentOutOfRangeException [if]
startIndex plus length indicates a
position not within this instance.
-or-
startIndex or length is less than
zero.
Tested code:
Dim FromIp As String = "192.168.1.1"
Dim str As String
str = FromIp.Substring(FromIp.LastIndexOf(".") + 1).ToString()
MessageBox.Show(str)
You must add 1 to LastIndexOf to skip the dot
There no need put the lenght of the Substring when you want all the rest of the string
But this refactored code will work better:
Dim FromIp As String = "192.168.1.1"
Dim IpPart As String() = FromIp.Split(".")
MessageBox.Show(IpPart(3))
FromIP.Text.LastIndexOf(".") + 1
instead of
FromIP.Text.LastIndexOf(".")
and
FromIP.TextLength-FromIP.Text.LastIndexOf(".")
is the last parameter instead of
FromIP.TextLength
As far as I remember, Substring takes Start,Stop as parameters.
So that would be: txt.Substring(IndexOf, txt.Length - IndexOf) or just with one parameter: Substring(IndexOf + 1)