How to get ASCII values of a string in VB.net - 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

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

VB.net Trying to get text between first and second slashs only

I am trying to retrive the value of the text between the first and second backslashes... but my coding skills have brought me this far and no futher.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim TEST As String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim splitted = TEST.Split("\"c)
Dim values = splitted.Skip(1).Take(splitted.Length - 2).ToArray()
MsgBox(values)
End Sub
Use regular expressions
Dim TEST as String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim matches As MatchCollection = Regex.Matches(TEST, "\\(.|\n)*?\\", RegexOptions.IgnoreCase)
Now if you want those values to come out in message boxes
For Each ma As Match In matches
MsgBox(ma.ToString.Trim({"\"c}))
Next
This will get you both "TWO" and "FOR". If you want just "TWO" then matches(0) is all you need.
Alternatively, if you just want to get the matches into an array in one line, then have each value of the array in a single message box:
Dim values = Regex.Matches(TEST, "\\(.|\n)*?\\").Cast(Of Match)().[Select](Function(m) m.Value).ToArray()
MsgBox(String.Join(", ", values))
Use the Split function. It will split on a string and store the separated values in an array. This is the easiest of all the answers here and is probably the most correct way of doing this.
This is the VB way of doing it:
Dim s() As String = Split("ONE\TWO\TRHREE\FOR\FIVE", "\")
MessageBox.Show(s(1))
And this is the .NET way of doing it:
Dim mainString As String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim s() As String = mainString.Split("\")
MessageBox.Show(s(1))
If you want "Two" as result, this should be the simplest approach:
Dim allToken As String() = "ONE\TWO\TRHREE\FOR\FIVE".Split("\"c)
Dim relevantPart = allToken.Skip(1).Take(1)
Dim result As String = String.Concat(relevantPart) ' "Two"
If you don't want a single string but a String() use ToArray:
Dim result As String() = relevantPart.ToArray()
Side-Note: you can't output an array directly, you could use String.Join:
MsgBox(String.Join(", ", result)) ' f.e. comma separated

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

String Manipulation with no delimiter

I have a string where I need to replace every character in that string with another value. That string has no delimiter. Is it possible to step through that string and replace every value with a set of predetermined values? I would like to keep it to one function as it is going to live within SSRS
Dim stringToChange As String = "123456ALWRYA"
I would then have to step through the string and replace all off the current values with new ones.
i.e. A=001, B=002, 1=101, 2=102, etc.
Is this possible if the string does not have a delimiter?
Thanks in advance!
SSRS Custom code has a pretty limited dialect, but this worked for me.
Add the following to the report Custom Code:
Function SingleReplace (SingleChar As String) As String
Select Case SingleChar
Case "A"
SingleReplace = "001"
Case "B"
SingleReplace = "002"
Case Else
SingleReplace = SingleChar
End Select
End Function
Function CustomReplace (BaseString As String) As String
Dim NewString As New System.Text.StringBuilder
For Each SingleChar As Char in BaseString
NewString.Append(SingleReplace(SingleChar))
Next
Return NewString.ToString()
End Function
Call this in a report expression with:
=Code.CustomReplace(Fields!MyString.Value)
Works for me in a simple report/table:
This is basically what Styxxy suggested...with a Dictionary for the looking up the values:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim stringToChange As String = "123456ALWRYA"
Debug.Print(stringToChange)
Dim changedString = ConvertString(stringToChange)
Debug.Print(changedString)
End Sub
Private Function ConvertString(ByVal inStr As String) As String
Static dict As New Dictionary(Of Char, String)
If dict.Count = 0 Then
dict.Add("A"c, "001")
dict.Add("B"c, "002")
dict.Add("1"c, "101")
dict.Add("2"c, "102")
' ... etc ...
End If
Dim sb As New System.Text.StringBuilder
For Each c As Char In inStr.ToUpper
If dict.ContainsKey(c) Then
sb.Append(dict(c))
Else
' ... possibly throw an exception? ...
sb.Append(c)
End If
Next
Return sb.ToString
End Function

VB.NET AlphaNumeric into integer

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