Find the index of a char in string? - vb.net

I have a string that goes like "abcdefg..."
I would like to find the index where the letter d is at, so I can get the number 3.
I managed to do it by looping through each letter in the string, but that doesn't sound very convenient. Is there another way?

The String class exposes some methods to enable this, such as IndexOf and LastIndexOf, so that you may do this:
Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then
End If

Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim myString As String = "abcdef"
Dim numberString As String = String.Empty
If myString.Contains("d") Then
numberString = myString.IndexOf("d")
End If
End Sub
Another sample with TextBox
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim myString As String = "abcdef"
Dim numberString As String = String.Empty
If myString.Contains(me.TextBox1.Text) Then
numberString = myString.IndexOf(Me.TextBox1.Text)
End If
End Sub
Regards

"abcdefgh..".IndexOf("d")
returns 3
In general returns first occurrence index, if not present returns -1

Related

How to compare textbox value to txt file

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim linenumber0 As Integer
linenumber0 = 0
Dim mass As Double
mass = (File.ReadAllLines("225.txt").ElementAt(linenumber0).ToString)
If (Math.Abs((cDbl(TextBox1.Text) - mass < 0.5) Then
TextBox1.BackColor = Color.Green
End If
Im getting an error conversing from string to double is not valid. It is probably a simple solution but i cant see it right now
Your error occurs because the data read from the file is a String, however you are attempting to assign it to a variable declared as Double.
You can use TryParse to convert the String to Double, avoid errors and provide appropriate feedback.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim lineNumber0 As Integer
Dim mass As Double
Dim input As Double
If Double.TryParse(File.ReadAllLines("225.txt").ElementAt(linenumber0), mass) Then
If Double.TryParse(TextBox1.Text, input) AndAlso Math.Abs(input - mass) < 0.5 Then
TextBox1.BackColor = Color.Green
End If
Else
'Bad file input
End If
'...
End Sub
I think that when you set the value to mass is catching a String, so parse it with a simple CDbl, like this
mass = cDbl(File.ReadAllLines("225.txt").ElementAt(linenumber0).ToString)
I supose that with this fix it will works.
Just in case, surround it with a TRY CATCH in case what it reads is not valid

Create a function that separates the characters of a word by symbols

I want to create a function where, for example, if I put the word visual in the input box I have to select from the ComboBox one of these 3 symbols: space, . , or *, in the output box I want the result of the word visual to come out like this: v.i.s.u.a.l or v i s u a l
I already know how to output a result that separates the string by a space but I don't know how to do it using a ComboBox with 3 symbols
This is the code I used for separating with a space
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim n As Integer
Dim str As String = "mis programing II"
Dim str2 As String = ""
Dim cc As String
For i = 1 To Len(str)
cc = Mid(str, i, 1)
str2 = str2 & cc & " "
Next
MsgBox(str2)
End Sub
End Class
You can use String.Join like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = "mis programing II"
Dim str2 As String = String.Join(str.ToCharArray(), ComboBox1.Text)
MsgBox(str2)
End Sub
I assumed the seperator has been selected in the ComboBox. Else, replace ComboBox1.Text with the seperator you want to use.
Update
Thanks to #JQSOFT, I just confirmed that String.Join does not work on Char arrays. Well here's another solution.
Dim str As String = "mis programing II"
Dim listX As New List(Of String)
Dim act As Action(Of Char) = Sub(c) listX.Add(CStr(c))
For Each c As Char In str.ToCharArray()
act.Invoke(c)
Next
Dim str2 As String = String.Join(".", listX.ToArray)
Console.WriteLine(str2)
Nice exercise:
Can be done using LINQ as follows:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = txtInput.Text '"mis programing II" for this example..
Dim sep As Char
'Validate your inputs:
If String.IsNullOrWhiteSpace(str) OrElse
Not Char.TryParse(cmbSep.Text, sep) Then
Return
End If
'and in one line:
Dim str2 = String.Join("", str.Split(" "c).
SelectMany(Function(x) x.ToCharArray.Append(" "c)).
Select(Function(x) $"{x}{If(Char.IsWhiteSpace(x), " ", sep)}")).
Replace($"{sep} ", " ").Trim
MessageBox.Show(str2)
End Sub
If you are not allowed to use LINQ, then the next snippet will do the same:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = txtInput.Text '"mis programing II" for this example..
Dim sep As Char
'Validate your inputs:
If String.IsNullOrWhiteSpace(str) OrElse
Not Char.TryParse(cmbSep.Text, sep) Then
Return
End If
Dim str2 As New StringBuilder
For Each word In str.Split(" "c)
For i = 0 To word.Length - 2
str2.Append(word(i)).Append(sep)
Next
str2.Append(word(word.Length - 1)).Append(" ")
Next
MessageBox.Show(str2.ToString.Trim)
End Sub
Some outputs:
m.i.s p.r.o.g.r.a.m.i.n.g I.I
m^i^s p^r^o^g^r^a^m^i^n^g I^I
m*i*s p*r*o*g*r*a*m*i*n*g I*I
m-i-s p-r-o-g-r-a-m-i-n-g I-I
m_i_s p_r_o_g_r_a_m_i_n_g I_I
m i s p r o g r a m i n g I I

Convert each String in ListBox1 to Integer and add to ListBox2: Incorrectly formatted input string

I have one TextBox, two ListBoxes and two Buttons. The first Button separates each String in the TextBox and adds them one by one to ListBox1. The second Button converts each String in to an Integer. But I get an exception thrown by the debugger:
Incorrectly formatted input string.
System.FormatException was unhandled
HResult=-2146233033
Message=Cadeia de caracteres de entrada com formato incorrecto.
Source=mscorlib
StackTrace:
em System.Number.StringToNumber(String str, NumberStyles options,
NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
em System.Number.ParseDecimal(String value, NumberStyles options,
NumberFormatInfo numfmt)
em System.Convert.ToDecimal(String value)
em g_.Form2.Button2_Click(Object sender, EventArgs e) em
C:\Users\Utilizador\Documents\Visual Studio
2012\Projects\g+\g+\Form2.vb:line 17
I have inserted code to clean the empty spaces but it continues to throw the same error.
After to reflecting to the problem i have decide to change the way to do it
This is my code:
Public Class Form2
Dim frequency
Dim interval
Dim textconverted
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myArray() As Char
myArray = Me.TextBox1.Text.ToCharArray
For Each chr As Char In Me.TextBox1.Text
ListBox1.Items.Add(chr)
Next
For i As Integer = ListBox1.Items.Count - 1 To 0 Step -1
If ListBox1.GetItemText(ListBox1.Items(i)) = String.Empty Then
ListBox1.Items.RemoveAt(i)
End If
Next i
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For i As Integer = 0 To ListBox1.Items.Count - 1
If (ListBox1.Items(i).ToString.Contains("a")) Then
ListBox2.Items.Add("1") 'Indexing is zero-based
Exit For
End If
Next
End Sub
End Class
Well i find a different way to do it and its do what i need.
This is the working solution
Public Class Form2
Dim frequency
Dim interval
Dim textconverted
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myArray() As Char
myArray = Me.TextBox1.Text.ToCharArray
For Each chr As Char In Me.TextBox1.Text
ListBox1.Items.Add(chr)
Next
For i As Integer = ListBox1.Items.Count - 1 To 0 Step -1
If ListBox1.GetItemText(ListBox1.Items(i)) = String.Empty Then
ListBox1.Items.RemoveAt(i)
End If
Next i
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myVariable As String = "foo"
For x As Integer = 0 To ListBox1.Items.Count - 1
If ListBox1.Items(x) = "a" Then
ListBox2.Items.Add("1")
End If
If ListBox1.Items(x) = "b" Then
ListBox2.Items.Add("2")
End If
If ListBox1.Items(x) = "c" Then
ListBox2.Items.Add("3")
End If
Next
End Sub
End Class
But now i have other problem with it it only check one string
How can i verify multiple strings there?
I added .ToString to your button 2 code and it worked fine. Turn on Option Strict; you will avoid some runtime errors. I have posted code that will handle a-z instead of a bunch of if statements. Add .ToLower to your TextBox1.Text.ToLower myArray is never used neither is myVariable.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For x As Integer = 0 To ListBox3.Items.Count - 1
Dim s As String = (Asc(ListBox3.Items(x).ToString) - 96).ToString
ListBox2.Items.Add(s)
Next
End Sub

VB.net invalid length for a base 64 char array or string

I have an issue with conversion from a base-64 string to normal, readable text. I did some research and found that base 64 strings have to be of a length that is a multiple of 4. So I used padRight to give it a valid length, but I keep getting the same error. For example, I enter "hi" and it encodes as "⚫aGk====", which seems like 8 characters to me (which is obviously a multiple of 4). When I try to read it, it reads in with a length of 1.
I'm also using a custom file extension that I just called ".bgs". I'm not sure if that does anything. Writing to this file as a base64 string and reading/decoding it is the only thing I'm trying to do.
Here is my code:
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using bs As New BinaryWriter(File.Open("saveFile.bgs", FileMode.Create))
Dim originText As String = TextBox1.Text
Dim cipherText As String
Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(originText)
cipherText = Convert.ToBase64String(byteArray)
Dim realLength As Integer = cipherText.Length() + 1
Dim len As Integer = (realLength Mod 4)
If (len > 0) Then bs.Write(cipherText.PadRight(realLength + (3 - len), "="))
bs.Close()
End Using
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Using bs As New BinaryReader(File.Open("saveFile.bgs", FileMode.Open))
Dim cipherText2 As String = bs.Read()
Dim originText2 As String = "Failed"
TextBox2.Text = cipherText2.Length() 'reports length of 1
Try
Dim byteArray2 As Byte() = Convert.FromBase64String(cipherText2)
originText2 = System.Text.Encoding.UTF8.GetString(byteArray2)
Catch ex As Exception
End Try
'TextBox2.Text = originText2
End Using
End Sub
Any help is much appreciated!
Update: it looks like the first character (the dot in the case above) seen in the .bgs file when I open it with notepad controls the contents of cipherText2, which is just a number, explaining why the length is so low.
Base64 encodes using only printable ASCII characters.
You are seeing the dot because you are using binary writer which prefixes strings with their length when writing to file.
Then you are using Read instead of ReadString so you read the string length as a number (which is then implicitly converted to string because you are not using Option Strict On like you should).
You can fix it by using ReadString instead of Read, but it would be easier if you used a text writer.
You also should not try to pad results of ToBase64String. It already gives you the correct string.
I would rewrite your code as:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim originText As String = TextBox1.Text
Dim cipherText As String = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(originText))
System.IO.File.WriteAllText("saveFile.bgs", cipherText, System.Text.Encoding.ASCII)
End Sub
Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Dim cipherText2 As String = System.IO.File.ReadAllText("saveFile.bgs", System.Text.Encoding.ASCII)
Dim originText2 As String = "Failed"
originText2 = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(cipherText2))
'TextBox2.Text = originText2
End Sub

How do I make a button perform multiple clicks with one label

I am trying to make a program similar to the startup tips which pop up when you open a program.I created a label for the text to be displayed,first string works but if I add the rest the last string overwrites all the previous ones in the label.Below is my code.
Public Class Form1
Dim string1 As String = "Hello "
Dim string2 As String = "world"
Dim string3 As String = "next text"
Dim string4 As String = "text4"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
lblDisplay.Text = string1
lblDisplay.Text = string2
End Sub
End Class
This will display each string as you click the button. It creates a String array string1 from the text then as the button is clicked, it displays each item in the array while keeping track of the item count in tipcnt. If tipcnt = string1.Count, it resets back to 0. If you have more strings to display, just append them to the array.
Public Class Form1
Dim string1 As String() = {"Hello", "world", "next text", "text4"}
Dim tipcnt As Integer = 0
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
lblDisplay.Text = string1(tipcnt)
tipcnt += 1
If tipcnt = string1.Count Then tipcnt = 0
End Sub
End Class