Finding the position of a character in a string - vb.net

I need to add a code (123456) into a line of text in a file.
\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\
The code needs to be entered after the 3rd "\" so it would look something like this.
\\ESSEX [D]\123456\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\
The text is always located on line 124 of the file.

If the [D] is always there a short and easy way would be to do:
Dim MyString As String = "\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\"
MyString = MyString.Insert(MyString.IndexOf("[D]") + 3, "123456")
Otherwise you could do:
Dim MyString As String = "\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\"
Dim d As Integer = 0
For Each i As Match In Regex.Matches(MyString, "\\")
If d = 2 Then
MsgBox(MyString.Insert(i.Index + 1, "132456"))
End If
d = d + 1
Next

You can use File.ReadAllLines and File.WriteAllLines and string methods:
Dim lines = File.ReadAllLines(path)
If lines.Length < 124 Then Return
Dim line = lines(123)
Dim tokens = line.Split(New String() {"\"}, StringSplitOptions.None)
If tokens.Length < 4 Then Return
tokens(3) = "123456"
lines(123) = String.Join("\", tokens)
File.WriteAllLines(path, lines)

I would just loop through the string, counting the occurrences of the backslash and then exiting when you have found the third occurrence.
You would need to keep count of the index and then use this with the String.Insert method to insert the "123456" code:
Dim s As String = "\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\"
Dim count As Integer = 0
Dim index As Integer = 0
For Each c In s
If c = "\" Then count += 1
index += 1
If count = 3 Then Exit For
Next
s = s.Insert(index, "123456")
Output:
\\ESSEX [D]\123456\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\

Related

Split text lines into words and decide which one is correct based on voting

The following code splits each lines into words and store the first words in each line into array list and the second words into another array list and so on. Then it selects the most frequent word from each list as correct word.
Module Module1
Sub Main()
Dim correctLine As String = ""
Dim line1 As String = "Canda has more than ones official language"
Dim line2 As String = "Canada has more than one oficial languages"
Dim line3 As String = "Canada has nore than one official lnguage"
Dim line4 As String = "Canada has nore than one offical language"
Dim wordsOfLine1() As String = line1.Split(" ")
Dim wordsOfLine2() As String = line2.Split(" ")
Dim wordsOfLine3() As String = line3.Split(" ")
Dim wordsOfLine4() As String = line4.Split(" ")
For i As Integer = 0 To wordsOfLine1.Length - 1
Dim wordAllLinesTemp As New List(Of String)(New String() {wordsOfLine1(i), wordsOfLine2(i), wordsOfLine3(i), wordsOfLine4(i)})
Dim counts = From n In wordAllLinesTemp
Group n By n Into Group
Order By Group.Count() Descending
Select Group.First
correctLine = correctLine & counts.First & " "
Next
correctLine = correctLine.Remove(correctLine.Length - 1)
Console.WriteLine(correctLine)
Console.ReadKey()
End Sub
End Module
My Question: How can I make it works with lines of different number of words. I mean that the length of each lines here is 7 words and the for loop works with this length (length-1). Suppose that line 3 contains 5 words.
EDIT: Accidentally had correctIndex where shortest should have been.
From what I can tell you are trying to see which line is the closest to the correctLine.
You can get the levenshtein distance using the following code:
Public Function LevDist(ByVal s As String,
ByVal t As String) As Integer
Dim n As Integer = s.Length
Dim m As Integer = t.Length
Dim d(n + 1, m + 1) As Integer
If n = 0 Then
Return m
End If
If m = 0 Then
Return n
End If
Dim i As Integer
Dim j As Integer
For i = 0 To n
d(i, 0) = i
Next
For j = 0 To m
d(0, j) = j
Next
For i = 1 To n
For j = 1 To m
Dim cost As Integer
If t(j - 1) = s(i - 1) Then
cost = 0
Else
cost = 1
End If
d(i, j) = Math.Min(Math.Min(d(i - 1, j) + 1, d(i, j - 1) + 1),
d(i - 1, j - 1) + cost)
Next
Next
Return d(n, m)
End Function
And then, this would be used to figure out which line is closest:
Dim correctLine As String = ""
Dim line1 As String = "Canda has more than ones official language"
Dim line2 As String = "Canada has more than one oficial languages"
Dim line3 As String = "Canada has nore than one official lnguage"
Dim line4 As String = "Canada has nore than one offical language"
Dim lineArray As new ArrayList
Dim countArray As new ArrayList
lineArray.Add(line1)
lineArray.Add(line2)
lineArray.Add(line3)
lineArray.Add(line4)
For i = 0 To lineArray.Count - 1
countArray.Add(LevDist(lineArray(i), correctLine))
Next
Dim shortest As Integer = Integer.MaxValue
Dim correctIndex As Integer = 0
For i = 0 To countArray.Count - 1
If countArray(i) <= shortest Then
correctIndex = i
shortest = countArray(i)
End If
Next
Console.WriteLine(lineArray(correctIndex))

Getting the character that inside the brackets

This is my string:
Dim value as string = "IR_10748(1).jpg"
How can I get this number 1 into another variable? I am thinking to use split.
How I can use to get this value in vb.net?
See String.Substring(Integer, Integer) and String.IndexOf(String).
Dim value As String = "IR_10748(1).jpg"
Dim startIndex As Integer = value.IndexOf("(") + 1
Dim length As Integer = value.IndexOf(")") - startIndex
Dim content As String = value.Substring(startIndex, length)
Regular expressions might be cleaner. This should work:
dim Result as string = Regex.Match(value, "(?<=\().*(?=\))").Value
It'll extract one or more characters contained between the parentheses.
Try this:
Dim value as String = "IR_10748(1).jpg"
Dim splitStrings() as String
'Split on either opening or closing parenthesis -
'This will give 3 strings - "IR_10748","1",".jpg"
splitStrings = value.Split(New String() {"(",")"}, StringSplitOptions.None)
'Parse as integer if required
Dim i as Integer
i = Integer.Parse(splitStrings(1))
Demo
It's not the prettiest, but this gets "1" using Remove and Split :
Dim value as String = "IR_10748(1).jpg"
Dim num As String = value.Remove(0, value.IndexOf("(") + 1).Split(")")(0)
That gives num = "1"
You can get the number more reliably than using String.Split. You'll want to use LastIndexOf to get the final opening parenthesis just in case you have a filename like "a(whatever)(1).ext", and you should inspect the filename without its extension, in case you have a filename like "a(1).(9)":
Dim value As String = "IR_10748(1).jpg"
Dim fn = Path.GetFileNameWithoutExtension(value)
Dim lastOpen = fn.LastIndexOf("(")
If lastOpen >= 0 Then
Dim length = fn.IndexOf(")", lastOpen + 1) - lastOpen - 1
If length >= 1 Then
Dim numAsString = fn.Substring(lastOpen + 1, length)
Console.WriteLine(numAsString)
ElseIf length = 0 Then
' do something if required
Console.WriteLine("No number in the parentheses.")
Else
' do something if required
Console.WriteLine("No closing parenthesis.")
End If
Else
' do something if required
Console.WriteLine("No opening parenthesis.")
End If

Find the length of a word in an array - Visual Basic

I have a richtextbox and I converted the words to an array, then I have code that will take the length and the output it... only problem is I don't know how to loop through all the different values of the array to check the length of each individual part of the array.
(I have this set on TextChanged)
Dim len1, len2, len3, len4, len5, len6, len7, len8, len9, len10, len11, len12, len13, len14, len15 As Integer
Dim input As String
Dim words As String()
Dim length As Integer
input = RichTextBox1.Text
words = input.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)
For Each w In words
length = Len(w)
Select Case length
Case 1
len1 = len1 + 1
Case 2
len2 = len2 + 1
Case 3
len3 = len3 + 1
Case 4
len4 = len4 + 1
Case 5
len5 = len5 + 1
Case 6
len6 = len6 + 1
Case 7
len7 = len7 + 1
Case 8
len8 = len8 + 1
Case 9
len9 = len9 + 1
Case 10
len10 = len10 + 1
Case 11
len11 = len11 + 1
Case 12
len12 = len12 + 1
Case 13
len13 = len13 + 1
Case 14
len14 = len14 + 1
Case 15
len15 = len15 + 1
End Select
Next
letcount.onelet.Text = Val(len1)
letcount.twolet.Text = Val(len2)
letcount.threelet.Text = Val(len3)
letcount.fourlet.Text = Val(len4)
letcount.fivelet.Text = Val(len5)
letcount.sixlet.Text = Val(len6)
letcount.sevenlet.Text = Val(len7)
letcount.eightlet.Text = Val(len8)
letcount.ninelet.Text = Val(len9)
letcount.tenlet.Text = Val(len10)
letcount.elevenlet.Text = Val(len11)
letcount.twelevelet.Text = Val(len12)
letcount.thirteenlet.Text = Val(len13)
letcount.fourteenlet.Text = Val(len14)
letcount.fifteenlet.Text = Val(len15)
bendataclear showed you how to use a For Next loop. If you can use LINQ, you can use the following code:
Sub Main
Dim words As String() = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" }
Dim lengthsOnly = words.Select(Function(w) w.Length).ToArray()
Dim wordsAndLengths = words.Select(Function(w) New With { .Word = w, .Length = w.Length }).ToArray()
End Sub
The first Select gets only the word lengths, the second returns an array with each word and it's length.
David,
Some clarification for you:
w is a string. The compiler determines the type at design time. See this S.O. thread
What does VB.Net For Each Loop look at to Infer the Type
Dim words() As String = {"0", "1", "2"}
For Each w In words
System.Windows.Forms.MessageBox.Show(w)
Next
The type is inferred by the compiler by looking at the elements in the IEnumerable collection (array, list, etc.) The intellisense even knows it's a string at design time, even when w looks like it is defined as a generic. Try it yourself...
BUT. You can of course add the type explicitly
Dim words() As String = {"0", "1", "2"}
For Each w As String In words
System.Windows.Forms.MessageBox.Show(w)
Next
The string array example doesn't really demonstrate the convenience of the shorthand. See below
Dim dictionaryOfDictionaries As New Dictionary(Of String, Dictionary(Of String, String))
For Each d As KeyValuePair(Of String, Dictionary(Of String, String)) In dictionaryOfDictionaries
' do something with each dictionary d
Next
' is identical to
For Each d In dictionaryOfDictionaries
' do something with each dictionary d
Next
You can ignore double spaces and enters because they are considered empty:
'HOW CAN I EXCLUDE DOUBLE SPACES
'AND INCLUDE IF SOMEBODY PRESSES ENTER?
words = input.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)
You could use another array?
Dim arr(14) as integer
Dim input As String
Dim words As String()
Dim length As Integer
input = RichTextBox1.Text
words = Split(input, " ")
For Each w in words
Dim l as Integer = Math.Min(Len(w) - 1,14)
arr(l) = arr(l) + 1
Next
Edit
In answer to questions in the comment:
w is a variable, and it is declared in the shortcut code For Each w in words
The shortcut declares a variable w then populates it with each member of the array words and runs the code between the For and next.
A longer way to do this without the shortcut would be something like:
Dim i as Integer
For i = 0 to words.GetUpperBound(0) -1
Dim w as string
w = words(i)
i = i + 1
'Rest of code
Next i
The next part Dim l as Integer = Math.Min(Len(w) - 1,14) sets l to the length of the word up to 14, as if we have a word longer than 15 letters it won't fit in the array.
Another way to do it would be:
Dim l as Integer
l = Len(w) - 1
If l > 14 then
l = 14
End If
arr(l) = arr(l) + 1

Separating Delimited Variable into array elements in VB.NET

I long variable in vb.net which contains the following information,
Dim g As String = "$C:\Program Files\Cavaj Java Decompiler\cavaj.exe$C:\Users\Yoosuf\AppData\Local\Google\Chrome\Application\chrome.exe$C:\Program Files\DVD Maker\dvdmaker.exe$C:\Program Files\Adobe\Adobe Photoshop CS2\ImageReady.exe$C:\Program Files\Java\jre6\bin\javaws.exe$"
The $ symbol is used as a delimiter to separate each item from the other. I need to add the exe file name at the end of each path to a listbox. However the initial process of retrieving the variable to individual array elements is not working properly.
Dim strArr() As String = g.Split("$") 'This variable is empty
For count = 0 To strArr.Length - 1
Dim arr As String = strArr(count).Split("\")
Dim strval As String = ""
For i As Integer = 3 To arr.Length - 1
strval = arr(i)
Dim j As Integer = arr.Length - 1
strval = arr(j)
Dim result As String = strval.Substring(g.Length - 5)
result = g.Substring(g.LastIndexOf("\") + 1)
ListBox1.Items.Add(result)
Next
Next
No need to do all this work. The System.IO.Path class has methods to do this for you. You want to use either System.IO.Path.GetFileName or System.IO.Path.GetFileNameWithoutExtension. Since you've already split all the file paths, just pass those paths to either of the aforementioned methods and add the result to your listbox.
Dim strArr() As String = g.Split("$")
For Each path As String In strArr
ListBox1.Items.Add(System.IO.Path.GetFileName(path))
Next
Please refer to the code below and the associated comments. Also I have comment out some code which I feel is not required based on what you want to do.
Dim strArr() As String = g.Split("$") 'This variable is empty
For count = 0 To strArr.Length - 1
Dim arr() As String = strArr(count).Split("\") ' Split returns an array
Dim strval As String = ""
For i As Integer = 3 To arr.Length - 1
'strval = arr(i)
Dim j As Integer = arr.Length - 1
strval = arr(j)
'Dim result As String = strval.Substring(g.Length - 5)
'result = g.Substring(g.LastIndexOf("\") + 1)
ListBox1.Items.Add(strval)
Next
Next

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