Split integer into array VB - vb.net

Good afternoon,
How can i split a value and insert it into a array in VB?
An example:
The initial value is 987654321.
Using a for loop i need to insert the value as something like this:
Position(1) = 9 'The first number from the splited integer
Position(2) = 8 'The second number from the splited integer
and so on...
Thank you.

This code is untested:
Dim x As Integer = 987654321
Dim s As String = x.ToString
Dim a(s.Length) As String
For i As Integer = 0 To s.Length - 1
a(i) = s.Substring(i, 1)
Next i

You could try:
Dim number As Integer = 987654321
Dim strText As String = number.ToString()
Dim charArr() As Char = strText.ToCharArray()
Once the numbers are separated, you can then pull them out from this array and convert them back to numbers if you need to.

Dim number As Integer = 987654321
Dim digits() As Integer = number.ToString().Cast(Of Integer)().ToArray()

Will show any number separated in 3 different message box.
You can make a function with the example to better suit your purpose.
Sub GetNumber()
Dim x As Integer, s As String
x = 987
s = LTrim(Str(x))
For i = 1 To Len(s)
MsgBox Mid(s, i, 1)
Next i
End Sub

I know this is an old question, but here is the most elegant solution I could get to work:
Dim key As Integer = 987654321
Dim digits() As Integer = System.Array.ConvertAll(Of Char, Integer)(key.ToString.ToCharArray, Function(c As Char) Integer.Parse(c.ToString))

Related

Number of indices is less than the number of dimensions of the indexed array in SSRS VBA Code

I have written below Code in SSRS Report and calling it from expression as =Code.convertCode(Parameters!ProcessingStatus.Value,"Reject,Fail")).Value , but on previewing report I am getting the error : "Number of indices is less than the number of dimensions of the indexed array"
Public Function convertCode(ParamValues As String, findString As String) As String()
Dim SrcArray() As String
Dim FndArray() As String
Dim DstArray() As String
Dim i As Integer
Dim j As Integer
Dim k As Integer
SrcArray() = Split(ParamValues, ",")
FndArray() = Split(FindString,",")
For k = LBound(FndArray) To UBound(FndArray)
For i = LBound(SrcArray) To UBound(SrcArray)
If (InStr(SrcArray(i), FndArray(k)) > 0) Then
ReDim Preserve DstArray(j) As String
DstArray(j) = SrcArray(i)
j = j + 1
End If
Next i
Next k
arr = DstArray
End Function
At the end of your function you have
arr = DstArray
which should be
convertCode = DstArray
Not sure if that's already the problem.
Note: Option Explicit would prevent this error.
I think the problem is that you're not declaring the first dimension in your arrays.
Dim SrcArray() As String
Dim FndArray() As String
Dim DstArray() As String
Should be:
Dim SrcArray(10) As String
Dim FndArray(10) As String
Dim DstArray(10) As String
Or whatever the number of the Array you'll need.
The error message indicates that the number of indices you have (none) is less that what you need (variables I, k, j).

I have three variables declared as strings, is there a way to randomly choose one? [duplicate]

This question already has answers here:
How can I randomly select one of three strings?
(2 answers)
Closed 8 years ago.
I have three strings, sUpperCase, sLowerCase and sNumbers. Each have either lower characters, upper characters or numbers. I need to know how to randomly choose one of these strings. I have thought maybe by assigning them a number but I am not sure how do to this without overriding the text inside of them. Maybe even an array but I'm not sure how to do this either. Can anybody help please?
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
ANSWER:
Function GeneratePassword() As String
'
' Declare two strings as the characters which the password can be created from
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
' Create a new random.
' Random is something which gets a random set of characters from a string.
Dim random As New Random
'
' Create sPassword as a new stringbuilder
' A stringbuilder is simply a class which builds a string from multiple characters
Dim sPassword As New StringBuilder
' Not random enough
'For i As Integer = 1 To 4
' Dim idxUpper As Integer = random.Next(0, sUpperCase.Length - 1)
' sPassword.Append(sUpperCase.Substring(idxUpper, 1))
' Dim idxNumber As Integer = random.Next(0, sNumbers.Length - 1)
' sPassword.Append(sNumbers.Substring(idxNumber, 1))
' Dim idxLower As Integer = random.Next(0, sLowerCase.Length - 1)
' sPassword.Append(sLowerCase.Substring(idxLower, 1))
'Next
' Random select Upper, lower or numeric
' Check for a max number of this(three if's to check for which one it was, might need or in if)
' If yes randomly select another one
' If no get random char from that type
' Add to password
' Is the password complete?
' If yes return password, if not repeat
Dim iCountUpper As Integer = 0
Dim iCountLower As Integer = 0
Dim iCountNumber As Integer = 0
Do Until sPassword.Length = 10
'Needed help for this bit
Dim x = New Random(Now.GetHashCode)
Dim y = {"sLowerCase", "sUpperCase", "sNumbers"}
Dim z = y(x.Next(0, y.Length))
If z.Contains("sLowerCase") And iCountUpper < 4 Then
Dim idxUpper As Integer = random.Next(0, sUpperCase.Length - 1)
sPassword.Append(sUpperCase.Substring(idxUpper, 1))
iCountUpper = iCountUpper + 1
ElseIf z.Contains("sUpperCase") And iCountLower < 4 Then
Dim idxLower As Integer = random.Next(0, sLowerCase.Length - 1)
sPassword.Append(sLowerCase.Substring(idxLower, 1))
iCountLower = iCountLower + 1
ElseIf z.Contains("sNumbers") And iCountNumber < 2 Then
Dim idxNumber As Integer = random.Next(0, sNumbers.Length - 1)
sPassword.Append(sNumbers.Substring(idxNumber, 1))
iCountNumber = iCountNumber + 1
Else
End If
Loop
'
' Return the password as a string
Return sPassword.ToString
End Function
You could do something like this:
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
Dim x = New Random(Now.GetHashCode)
Dim y = {sLowerCase, sUpperCase, sNumbers}
Dim z = y(x.Next(0, y.Length))
Debug.Print(z)
Dim strings = {"qwertyuiopasdfghjklzxcvbnm", "MNBVCXZLKJHGFDSAPOIUYTREWQ", "1234567890"}
Dim selected As String
Dim Generator As System.Random = New System.Random()
selected = strings(Generator.Next(0, strings.GetUpperBound(0)))
Create an array with your strings:
Dim array As String() = New String() {sLowerCase, sUpperCase, sNumbers}
Use Random class to generate random number between 0 and the array lenght:
Dim random As Random = New Random(DateTime.Now.Ticks)
Dim randomChoose As String = array(random.Next(0, array.Length - 1))
Select a random char:
Dim ch As Char = randomChoose(random.Next(0, randomChoose.Length - 1))

vb.net generate random number and string

I want to generate a random number of 6 intergers in vb.net which should be number and also some times alphanumerice.Like ist 4 or 5 numbers should be numbers and next should be alphnumeric.I created both numbers separatedly.like this
Public Function rand() As String
'Number
Dim rng As Random = New Random
Dim number As Integer = rng.Next(1, 1000000)
Dim digits As String = number.ToString("000000")
'Alphnumeric
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 5
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
End Function
Now Any One Give Me Idea that in this function can i return number and some times string or may b a single instances which create both numbers and strings.
The first problem to solve is the random number generator. You should use only one instance and not multiple instances that gives back the same sequence if called in short time distance. Then it is
difficult to say what 'something' means in your requirements, but supposing you are fine with rougly 70% numbers and 30% a mix of numbers and strings then you call the random generator to decide for a sequence of only numbers or a mixed one. Based on the output of the random selection of the sequence build from the appropriate string
' A global unique random generator'
Dim rng As Random = New Random
Sub Main
Console.WriteLine(rand())
Console.WriteLine(rand())
Console.WriteLine(rand())
Console.WriteLine(rand())
End Sub
Public Function rand() As String
Dim sb As New StringBuilder
' Selection of pure numbers sequence or mixed one
Dim pureNumbers = rng.Next(1,11)
if pureNumbers < 7 then
' Generate a sequence of only digits
Dim number As Integer = rng.Next(1, 1000000)
Dim digits As String = number.ToString("000000")
For i As Integer = 1 To 6
Dim idx As Integer = rng.Next(0, digits.Length)
sb.Append(digits.Substring(idx, 1))
Next
else
' Generate a sequence of digits and letters
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
For i As Integer = 1 To 6
Dim idx As Integer = rng.Next(0, 36)
sb.Append(s.Substring(idx, 1))
Next
End if
return sb.ToString()
End Function

generate random string

well i know that there are a lot of these threads but im new to vb.net yet i cant edit the sources given to make what i really want
so i want a function that will generate random strings which will contain from 15-32 characters each and each of them will have the following chars ( not all at the same string but some of them ) :
A-Z
a-z
0-9
here is my code so far
Functon RandomString()
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Change the string to include the a-z characters:
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Change the loop to create a random number of characters:
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Note that the upper boundary in the Next method is exclusive, so Next(15, 33) gives you a value that can range from 15 to 32.
Use the length of the string to pick a character from it:
Dim idx As Integer = r.Next(0, s.Length)
As you are going to create random strings, and not a single random string, you should not create the random number generator inside the function. If you call the function twice too close in time, you would end up with the same random string, as the random generator is seeded using the system clock. So, you should send the random generator in to the function:
Function RandomString(r As Random)
So, all in all:
Function RandomString(r As Random)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Dim sb As New StringBuilder
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Usage example:
Dim r As New Random
Dim strings As New List<string>()
For i As Integer = 1 To 10
strings.Add(RandomString(r))
Next
Try something like this:-
stringToReturn&= Guid.NewGuid.ToString().replace("-","")
You can also check this:-
Sub Main()
Dim KeyGen As RandomKeyGenerator
Dim NumKeys As Integer
Dim i_Keys As Integer
Dim RandomKey As String
''' MODIFY THIS TO GET MORE KEYS - LAITH - 27/07/2005 22:48:30 -
NumKeys = 20
KeyGen = New RandomKeyGenerator
KeyGen.KeyLetters = "abcdefghijklmnopqrstuvwxyz"
KeyGen.KeyNumbers = "0123456789"
KeyGen.KeyChars = 12
For i_Keys = 1 To NumKeys
RandomKey = KeyGen.Generate()
Console.WriteLine(RandomKey)
Next
Console.WriteLine("Press any key to exit...")
Console.Read()
End Sub
Using your function as a guide, I modified it to:
Randomize the length (between minChar & maxCharacters)
Randomize the string produced each time (by using the static Random)
Code:
Function RandomString(minCharacters As Integer, maxCharacters As Integer)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(minCharacters, maxCharacters)
Dim sb As New StringBuilder
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
Return sb.ToString()
End Function
Try this out:
Private Function RandomString(ByRef Length As String) As String
Dim str As String = Nothing
Dim rnd As New Random
For i As Integer = 0 To Length
Dim chrInt As Integer = 0
Do
chrInt = rnd.Next(30, 122)
If (chrInt >= 48 And chrInt <= 57) Or (chrInt >= 65 And chrInt <= 90) Or (chrInt >= 97 And chrInt <= 122) Then
Exit Do
End If
Loop
str &= Chr(chrInt)
Next
Return str
End Function
You need to change the line For i As Integer = 1 To 8 to For i As Integer = 1 To ? where ? is the number of characters long the string should be. This changes the number of times it repeats the code below so more characters are appended to the string.
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
My $.02
Dim prng As New Random
Const minCH As Integer = 15 'minimum chars in random string
Const maxCH As Integer = 35 'maximum chars in random string
'valid chars in random string
Const randCH As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Private Function RandomString() As String
Dim sb As New System.Text.StringBuilder
For i As Integer = 1 To prng.Next(minCH, maxCH + 1)
sb.Append(randCH.Substring(prng.Next(0, randCH.Length), 1))
Next
Return sb.ToString()
End Function
please note that the
r.Next(0, 35)
tend to hang and show the same result Not sure whay; better to use
CInt(Math.Ceiling(Rnd() * N)) + 1
see it here Random integer in VB.NET
I beefed up Nathan Koop's function for my own needs, and thought I'd share.
I added:
Ability to add Prepended and Appended text to the random string
Ability to choose the casing of the allowed characters (letters)
Ability to choose to include/exclude numbers to the allowed characters
NOTE: If strictly looking for an exact length string while also adding pre/appended strings you'll need to deal with that; I left out any logic to handle that.
Example Usages:
' Straight call for a random string of 20 characters
' All Caps + Numbers
String_Random(20, 20, String.Empty, String.Empty, 1, True)
' Call for a 30 char string with prepended string
' Lowercase, no numbers
String_Random(30, 30, "Hey_Now_", String.Empty, 2, False)
' Call for a 15 char string with appended string
' Case insensitive + Numbers
String_Random(15, 15, String.Empty, "_howdy", 3, True)
.
Public Function String_Random(
intMinLength As Integer,
intMaxLength As Integer,
strPrepend As String,
strAppend As String,
intCase As Integer,
bIncludeDigits As Boolean) As String
' Allowed characters variable
Dim s As String = String.Empty
' Set the variable to user's choice of allowed characters
Select Case intCase
Case 1
' Uppercase
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Case 2
' Lowercase
s = "abcdefghijklmnopqrstuvwxyz"
Case Else
' Case Insensitive + Numbers
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
End Select
' Add numbers to the allowed characters if user chose so
If bIncludeDigits = True Then s &= "0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(intMinLength, intMaxLength)
Dim sb As New StringBuilder
' Add the prepend string if one was passed
If String.IsNullOrEmpty(strPrepend) = False Then sb.Append(strPrepend)
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
' Add the append string if one was passed
If String.IsNullOrEmpty(strAppend) = False Then sb.Append(strAppend)
Return sb.ToString()
End Function

How to get an array to display all its values at once

Here is some sample code:
Dim arrValue(3) as Integer
arrValue(0) = 5
arrValue(1) = 4
arrValue(2) = 7
arrValue(3) = 1
How can I display those four values next to each other.
More specifically, given those values how can I make txtValue.Text = 5471
Edit:
The idea I had would be to use some sort of function to append each one to the end using a loop like this:
Dim finalValue
For i As Integer = 3 To 0 Step -1
arrValue(i).appendTo.finalValue
Next
Obviously that code wouldn't work though the premise is sound I don't know the syntax for appending things and I'm sure I wouldn't be able to append an Integer anyway, I would need to convert each individual value to a string first.
Another method is to use String.Join:
Sub Main
Dim arrValue(3) as Integer
arrValue(0) = 5
arrValue(1) = 4
arrValue(2) = 7
arrValue(3) = 1
Dim result As String = String.Join("", arrValue)
Console.WriteLine(result)
End Sub
If I understand your question correctly, you can use StringBuilder to append the values together.
Dim finalValue as StringBuilder
finalValue = new StringBuilder()
For i As Integer = 3 To 0 Step -1
finalValue.Append(arrValue(i))
Next
Then just return the finalValue.ToString()
Convert the integers to strings, and concatenate them:
Dim result as String = ""
For Each value as Integer in arrValue
result += value.ToString()
Next
Note: using += to concatenate strings performs badly if you have many strings. Then you should use a StringBuilder instead:
Dim builder as New StringBuilder()
For Each value as Integer in arrValue
builder.Append(value)
Next
Dim result as String = builder.ToString()
for i = lbound(arrValue) to ubound(arrValue)
ss=ss & arrValue(i)
next i
end for
debug.print ss
Dim value as string = ""
For A As Integer = 1 To Begin.nOfMarks
value += "Mark " & A & ": " & (Begin.Marks(A)) & vbCrLf
Next A