VB.NET AlphaNumeric into integer - vb.net

If Textbox1.text contains a string value of ZU4, how can I convert that string to it's numeric ASCII codes, and output it to a second text box?
I'd like to do this using a FOR LOOP conditional statement which will read every character in INPUT?
Sample:
INPUT Textbox1.Text = ZU4
OUTPUT Textbox2.Text = 908552

You could also use LINQ:
TextBox2.Text = String.Join(String.Empty, From c In Textbox1.Text.ToCharArray Select (Asc(c).ToString))
Could be useful on some job interviews... :)

All of the other answers will work with your given example, however, some of the suggestions are using unicode encoding rather than ASCII. If strictly adhering to ASCII encoding is important, then you should explicitly specify the encoding that you want to use.
Convert.ToInt32 uses UTF-16 encoding. I'm not sure what CInt will do, but I suspect it works the same way. Using Asc is better, but it is still dependent on the code page setting for the thread, so it's still not entirely safe. Besides that, Asc is an old VB6 function which is provided in VB.NET, primarily for backwards compatibility.
Therefore, I would recommend using the ASCIIEncoding class instead. You can get an instance of that class using the shared ASCII property of the Encoding class in the System.Text namespace, for instance:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
builder.Append(b.ToString())
Next
Return builder.ToString()
End Function
Then, you can call the function like this:
Textbox2.Text = ConvertTextToAsciiDigits(Textbox1.Text)
However, I can't imagine that the resulting string will be usable unless every character results in a two digit number. Therefore, I would force it to be two digits by doing something like this:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException() ' Throws an exception if the value is three digits
End If
builder.Append(b.ToString("00")) ' Adds a leading zero to one-digit values
Next
Return builder.ToString()
End Function
To add a hyphen after every fourth digit, as you mentioned in a comment below, you could just keep track of the total digits added since the last hyphen, like this:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
Dim digitsSinceHyphen As Integer = 0
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException()
End If
builder.Append(b.ToString("00"))
digitsSinceHyphen += 2
If digitsSinceHyphen >= 4 Then
builder.Append("-")
digitsSinceHyphen = 0
End If
Next
Return builder.ToString()
End Function

Here is one approach, in C#:
Textbox2.Text = string.Empty;
foreach(var c in Textbox1.Text)
{
Textbox2.Text += ((int)c).ToString();
}
VB.NET:
Textbox2.Text = String.Empty
For Each c As Char In Textbox1.Text
Textbox2.Text = Textbox2.Text + Convert.ToInt32(c).ToString()
Next
It:
Clears out Textbox2.Text
Loops over each character in the input
Concatenates the integer value output as a string to the output text

TextBox2.Text = ""
For i As Integer = 0 To TextBox1.TextLength - 1
TextBox2.Text += Asc(TextBox1.Text(i)).ToString()
Next

i modified the code from this Link
Function AsciiEncode(ByVal value As String) As String
Dim encValue As New System.Text.StringBuilder(value.Length * 6)
Dim c As Char
For Each c In value
encValue.Append(Convert.ToInt32(c))
Next
Return encValue.ToString()
End Function
usage:
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
TextBox2.Text = AsciiEncode(TextBox1.Text)
End Sub

Related

Get a specific value from the line in brackets (Visual Studio 2019)

I would like to ask for your help regarding my problem. I want to create a module for my program where it would read .txt file, find a specific value and insert it to the text box.
As an example I have a text file called system.txt which contains single line text. The text is something like this:
[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]
What i want to do is to get only the last name value "xxx_xxx" which every time can be different and insert it to my form's text box
Im totally new in programming, was looking for the other examples but couldnt find anything what would fit exactly to my situation.
Here is what i could write so far but i dont have any idea if there is any logic in my code:
Dim field As New List(Of String)
Private Sub readcrnFile()
For Each line In File.ReadAllLines(C:\test\test_1\db\update\network\system.txt)
For i = 1 To 3
If line.Contains("Last Name=" & i) Then
field.Add(line.Substring(line.IndexOf("=") + 2))
End If
Next
Next
End Sub
Im
You can get this down to a function with a single line of code:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Return File.ReadLines(fileName).Where(Function(line) RegEx.IsMatch(line, "[[[]Last Name=(?<LastName>[^]]+)]").Select(Function(line) RegEx.Match(line, exp).Groups("LastName").Value)
End Function
But for readability/maintainability and to avoid repeating the expression evaluation on each line I'd spread it out a bit:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Dim exp As New RegEx("[[[]Last Name=(?<LastName>[^]]+)]")
Return File.ReadLines(fileName).
Select(Function(line) exp.Match(line)).
Where(Function(m) m.Success).
Select(Function(m) m.Groups("LastName").Value)
End Function
See a simple example of the expression here:
https://dotnetfiddle.net/gJf3su
Dim strval As String = " [Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim strline() As String = strval.Split(New String() {"[", "]"}, StringSplitOptions.RemoveEmptyEntries) _
.Where(Function(s) Not String.IsNullOrWhiteSpace(s)) _
.ToArray()
Dim lastnameArray() = strline(1).Split("=")
Dim lastname = lastnameArray(1).ToString()
Using your sample data...
I read the file and trim off the first and last bracket symbol. The small c following the the 2 strings tell the compiler that this is a Char. The braces enclosed an array of Char which is what the Trim method expects.
Next we split the file text into an array of strings with the .Split method. We need to use the overload that accepts a String. Although the docs show Split(String, StringSplitOptions), I could only get it to work with a string array with a single element. Split(String(), StringSplitOptions)
Then I looped through the string array called splits, checking for and element that starts with "Last Name=". As soon as we find it we return a substring that starts at position 10 (starts at zero).
If no match is found, an empty string is returned.
Private Function readcrnFile() As String
Dim LineInput = File.ReadAllText("system.txt").Trim({"["c, "]"c})
Dim splits = LineInput.Split({"]["}, StringSplitOptions.None)
For Each s In splits
If s.StartsWith("Last Name=") Then
Return s.Substring(10)
End If
Next
Return ""
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = readcrnFile()
End Sub
You can easily split that line in an array of strings using as separators the [ and ] brackets and removing any empty string from the result.
Dim input As String = "[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim parts = input.Split(New Char() {"["c, "]"c}, StringSplitOptions.RemoveEmptyEntries)
At this point you have an array of strings and you can loop over it to find the entry that starts with the last name key, when you find it you can split at the = character and get the second element of the array
For Each p As String In parts
If p.StartsWith("Last Name") Then
Dim data = p.Split("="c)
field.Add(data(1))
Exit For
End If
Next
Of course, if you are sure that the second entry in each line is the Last Name entry then you can remove the loop and go directly for the entry
Dim data = parts(1).Split("="c)
A more sophisticated way to remove the for each loop with a single line is using some of the IEnumerable extensions available in the Linq namespace.
So, for example, the loop above could be replaced with
field.Add((parts.FirstOrDefault(Function(x) x.StartsWith("Last Name"))).Split("="c)(1))
As you can see, it is a lot more obscure and probably not a good way to do it anyway because there is no check on the eventuality that if the Last Name key is missing in the input string
You should first know the difference between ReadAllLines() and ReadLines().
Then, here's an example using only two simple string manipulation functions, String.IndexOf() and String.Substring():
Sub Main(args As String())
Dim entryMarker As String = "[Last Name="
Dim closingMarker As String = "]"
Dim FileName As String = "C:\test\test_1\db\update\network\system.txt"
Dim value As String = readcrnFile(entryMarker, closingMarker, FileName)
If Not IsNothing(value) Then
Console.WriteLine("value = " & value)
Else
Console.WriteLine("Entry not found")
End If
Console.Write("Press Enter to Quit...")
Console.ReadKey()
End Sub
Private Function readcrnFile(ByVal entry As String, ByVal closingMarker As String, ByVal fileName As String) As String
Dim entryIndex As Integer
Dim closingIndex As Integer
For Each line In File.ReadLines(fileName)
entryIndex = line.IndexOf(entry) ' see if the marker is in our line
If entryIndex <> -1 Then
closingIndex = line.IndexOf(closingMarker, entryIndex + entry.Length) ' find first "]" AFTER our entry marker
If closingIndex <> -1 Then
' calculate the starting position and length of the value after the entry marker
Dim startAt As Integer = entryIndex + entry.Length
Dim length As Integer = closingIndex - startAt
Return line.Substring(startAt, length)
End If
End If
Next
Return Nothing
End Function

Concat file format not supported

Using VB I am trying to create a name for the file by concatenating together the words "NewEmployeesOut" with the short date and time of the day. I am getting the following error System.NotSupportedException: 'The given path's format is not supported.' Below is the Code I am currently using, it seems like VB does not like a character I am using in my concat function when trying to export the .txt file.
Private Sub btnWrite_Click(sender As Object, e As EventArgs) Handles btnWrite.Click
Dim writeRecord As New StreamWriter
(New FileStream("NewEmployeesOut" & Date.Today.ToShortDateString & Date.Now.ToShortTimeString & ".txt", FileMode.Append, FileAccess.Write))
Dim EmployeeInformation1 As New EmployeeInformation()
writeRecord.Write(EmployeeInformation1.LastName & "|")
writeRecord.Write(EmployeeInformation1.FirstName & "|")
writeRecord.Write(EmployeeInformation1.DepartmentNo & "|")
writeRecord.Write(EmployeeInformation1.CreateUserName(EmployeeInformation1.FirstName, EmployeeInformation1.LastName) & "|")
writeRecord.WriteLine(EmployeeInformation1.CreatePassword)
writeRecord.Close()
End Sub
From MS docs https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
The following characters are resevered.
< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
A file name formatted as follows will pass muster. The uppercase HH gives you 24 hour time.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim fileName As String = "NewEmployeesOut" & Now.ToString(" MMMM dd, yyyy HH,mm") & ".txt"
Debug.Print(fileName)
File.CreateText(fileName)
End Sub
In the immediate window...
NewEmployeesOut December 10, 2020 18,07.txt
Your short date probably looks like "31/12/2020" or "12/31/2020" which are no valid file names. Try something like
Dim now As DateTime = DateTime.Now
Dim fileName As String = $"NewEmployeesOut_{now:yyyy-MM-dd}_{now:HHmm}.txt"
Concerning the other question: It's the wrong place to post it, don't ask another question within a comment.
I think you have to learn a bit the basics first, read/watch some VB.Net tutorials and maybe some clean-code principles like the clean-code-techniques. Your questions suggest that you don't know yet how to write simple code.
Try to structure what you are doing, avoid (like in your example) to copy 4 times the same lines of code but to create functions instead to encapsulate business logic. e.g. writing a file has nothing to do with assembling a file name, therefore the two things should not be conducted in the same method etc.
But this all said, here an idea how you could structure your code (from the comment not the main question), although I'm not too positive about the usability of the two random digits...
Usage:
Dim fileName As String = GetFileName("Smith", "John")
Methods/Properties:
Private Shared Function GetFileName(lastName As String, firstName As String) As String
lastName = NormalizeAndCrop(lastName, 7)
firstName = NormalizeAndCrop(firstName, 10)
Dim randomNumber As Int32 = Randomizer.Next(0, 100)
Return $"{lastName}{firstName}{randomNumber:00}"
End Function
Private Shared Function NormalizeAndCrop(text As String, length As Int32)
'Check args
If (length < 0) Then Throw New ArgumentOutOfRangeException(NameOf(length), length, "A non-negative value expected!")
If (text Is Nothing) OrElse (length = 0) Then Return String.Empty
text = text.Normalize()
'Copy only valid characters
Dim result As New StringBuilder()
For i As Int32 = 0 To text.Length - 1
Dim c As Char = text(i)
If (IsValidFileNameChar(c)) Then
result.Append(c)
If (result.Length = length) Then
Return result.ToString()
End If
End If
Next
Return result.ToString()
End Function
Private Shared Function IsValidFileNameChar(c As Char) As Boolean
If (Char.IsControl(c)) Then Return False
If (InvalidFileNameChars.IndexOf(c) > -1) Then Return False
Return True
End Function
Private Shared ReadOnly Property Randomizer As Random = New Random(Environment.TickCount)
Private Shared ReadOnly Property InvalidFileNameChars As String = New String(Path.GetInvalidFileNameChars())

I need help outputting squares of numbers separated by commas

Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
TextBox2.Text = TextBox1.Text ^ 2
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
TextBox1.Text = Nothing
TextBox2.Text = Nothing
End Sub
End Class
The code above outputs squares of any single values input in textbox1 but i need some help in inputting a couple of values separated by commas and then output the squares of those individual values eg 3,4 the output 9,16
I'm not going to do it all for you, because this looks like homework, but here are some pointers:
TextBox2.Text = TextBox1.Text ^ 2
1) Turn on Option Strict, by placing Option Strict On at the top of your code file or by putting it in the project properties Compile tab. This will help you be more rigorous with your coding. Here you're taking a string (TextBox1.Text) and having VB auto convert it to a number (which might fail), squaring it, and then auto converting it back to a string to store in TextBox2.Text. This is bad news all round; always be crystal clear in your own mind and explicit in your coding about the difference between various data types.A string containing numbers is not the same thing as a number!
2) Rename your textboxes after you drop them on a form. Nothing is more frustrating than to read a block of code where the variable names are irrelevant garbage. You will find this when you come back to some complex code in 6 months and think "what the..."; renaming a textbox so it is called resultTextBox or inputTextBox takes seconds and makes your code instantly more comprehensible to both you and anyone you call in to help out with it
separated by commas
The following line of code will split a string into an array of strings, on comma:
Dim csv = "3,6"
Dim arr = csv.Split(","c)
Console.WriteLine(arr(0)) 'prints 3
Console.WriteLine(arr(1)) 'prints 6
The following line of code will convert a string to an integer:
Dim s = "3"
Dim i = Convert.ToInt32(s)
Maths operations can now be performed on it
i = i * i 'square it
The following line of code will turn an integer into a string:
Dim i as Integer = 3
Dim s as String = i.ToString() 's is now "3"
The following line of code will loop through an array, appending the values in the array to a string variable, and adding commas. Finally it trims off the excess trailing comma
Dim s as New String
For Each x as String in arr
s = s & x & ","
Next x
s = s.TrimEnd(","c)
Here is another way too, using the String.Join helper method:
Dim s as String = String.Join(","c, arr)

How to find indexes for certain character in a string VB.NET

I'm beginner with VB.net.
How do I read indexes for certain character in a string? I read an barcode and I get string like this one:
3XXX123456-C-AA123456TY-667
From that code I should read indexes for character "-" so I can cut the string in parts later in the code.
For example code above:
3456-C
6TY-667
The length of the string can change (+/- 3 characters). Also the places and count of the hyphens may vary.
So, I'm looking for code which gives me count and position of the hyphens.
Thanks in advance!
Use the String.Splt method.
'a test string
Dim BCstring As String = "3XXX123456-C-AA123456TY-667"
'split the string, removing the hyphens
Dim BCflds() As String = BCstring.Split({"-"c}, StringSplitOptions.None)
'number of hyphens in the string
Dim hyphCT As Integer = BCflds.Length - 1
'look in the debuggers immediate window
Debug.WriteLine(BCstring)
'show each field
For Each s As String In BCflds
Debug.WriteLine(String.Format("{0,5} {1}", s.Length, s))
Next
'or
Debug.WriteLine(BCstring)
For idx As Integer = 0 To hyphCT
Debug.WriteLine(String.Format("{0,5} {1}", BCflds(idx).Length, BCflds(idx)))
Next
If all you need are the parts between hyphens then as suggested by dbasnett use the split method for strings. If by chance you need to know the index positions of the hyphens you can use the first example using Lambda to get the positions which in turn the count give you how many hyphens were located in the string.
When first starting out with .NET it's a good idea to explore the various classes for strings and numerics as there are so many things that some might not expect to find that makes coding easier.
Dim barCode As String = "3XXX123456-C-AA123456TY-667"
Dim items = barCode _
.Select(Function(c, i) New With {.Character = c, .Index = i}) _
.Where(Function(item) item.Character = "-"c) _
.ToList
Dim hyphenCount As Integer = items.Count
Console.WriteLine("hyphen count is {0}", hyphenCount)
Console.WriteLine("Indices")
For Each item In items
Console.WriteLine(" {0}", item.Index)
Next
Console.WriteLine()
Console.WriteLine("Using split")
Dim barCodeParts As String() = barCode.Split("-"c)
For Each code As String In barCodeParts
Console.WriteLine(code)
Next
Here is an example that'll split your string and allow you to parse through the values.
Private Sub TestSplits2Button_Click(sender As Object, e As EventArgs) Handles TestSplits2Button.Click
Try
Dim testString As String = "3XXX123456-C-AA123456TY-667"
Dim vals() As String = testString.Split(Convert.ToChar("-"))
Dim numberOfValues As Integer = vals.GetUpperBound(0)
For Each testVal As String In vals
Debug.Print(testVal)
Next
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
End Try
End Sub

How to get ASCII values of a string in VB.net

I want to be able so get the ASCII values of all the characters in a string.
I can get the ASCII value of a character but i cannot do it for the whole string.
My attempt:
dim input as string = console.readline()
dim value as integer = ASC(input)
'Then I am changing its value by +1 to write the input in a secret code form.
console.writeline(CHR(value+1))
I want to be able to get the ASCII values for all characters in the string so i can change the all letters in the string +1 character in the alphabet.
Any help appreciated, thanks.
Use Encoding.ASCII.GetBytes:
Dim asciis As Byte() = System.Text.Encoding.ASCII.GetBytes(input)
If you want to increase each letter's ascii value you can use this code:
For i As Int32 = 0 To asciis.Length - 1
asciis(i) = CByte(asciis(i) + 1)
Next
Dim result As String = System.Text.Encoding.ASCII.GetString(asciis)
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim a As Integer
a = Asc(TextBox1.Text)
MessageBox.Show(a)
End Sub
End Class
I know it's been almost three years now, but let me show you this.
Function to convert String to Ascii (You already have a String in your Code). You can use either (Asc) or (Ascw) ... for more information, please read Microsoft Docs
Dim Input As String = console.readline()
Dim Value As New List(Of Integer)
For Each N As Char In Input
Value.Add(Asc(N) & " ")
Next
Dim OutPutsAscii As String = String.Join(" ", Value)
Function to Convert Ascii to String (What you asked for). You can use either (Chr) or (ChrW) ... for more information, please read Microsoft Docs
Dim Value1 As New List(Of Integer)
Dim MyString As String = String.Empty
For Each Val1 As Integer In Value1
MyString &= ChrW(Val1)
Next