How to Replace string and loop between commas with another string - vb.net

can you help me how to get Index of the same string and replace it one by one with another string?
Here my example code :
For i As Integer = 0 To 10
Dim str As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim replace As String = "efgh"
Dim value As String
value = str.Replace("abcd", replace)
TextBox4.AppendText(value)
Next
The value will be result : efgh,efgh,efgh,efgh,efgh...
How i can create the result like this :
efgh,abcd,abcd,abcd,abcd,abcd...
for the next loop it will be like this :
abcd,efgh,abcd,abcd,abcd,abcd...
for the next loop it will be like this :
abcd,abcd,efgh,abcd,abcd,abcd...
Thank you

There are lots of ways this could be done. One perhaps inefficient way would be to split the string at the commas, replace the appropriate item in the resulting array, and then join the array back up.
Dim str As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim replace As String = "efgh"
For i As Integer = 0 To str.Count(Function(x) x = ","c)
Dim strParts = str.Split(","c)
strParts(i) = replace
Dim value As String = String.Join(",", strParts)
Console.WriteLine(value)
Next
Output:
efgh,abcd,abcd,abcd,abcd,abcd,abcd,abcd
abcd,efgh,abcd,abcd,abcd,abcd,abcd,abcd
abcd,abcd,efgh,abcd,abcd,abcd,abcd,abcd
abcd,abcd,abcd,efgh,abcd,abcd,abcd,abcd
abcd,abcd,abcd,abcd,efgh,abcd,abcd,abcd
abcd,abcd,abcd,abcd,abcd,efgh,abcd,abcd
abcd,abcd,abcd,abcd,abcd,abcd,efgh,abcd
abcd,abcd,abcd,abcd,abcd,abcd,abcd,efgh

As #Mark mentioned there are lots of ways this could be done. One of this ways to add and remove ranges in a string is to use the StringBuilder.
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 0 To 35 Step 5
Dim sDefaultString As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim sbText = New StringBuilder(sDefaultString)
sbText.Remove(i, 4)
sbText.Insert(i, "efgh")
TextBox1.AppendText(sbText.ToString & vbNewLine)
Next
End Sub
End Class

Related

Find all instances of a word in a string and display them in textbox (vb.net)

I have a string filled with the contents of a textbox (pretty large).
I want to search through it and display all occurances of this word. In addition I need the searchresult to display some charachters in the string before and after the actual searchterm to get the context for the word.
The code below is part of a code that takes keywords from a listbox one by one using For Each. The code displays the first occurance of a word together with the characters in front and after the word - and stop there. It will also display "no Match for: searched word" if not found.
As stated in the subject of this question - I need it to search the whole string and display all matches for a particular word together with the surrounding characters.
Where = InStr(txtScrape.Text, Search)
If Where <> 0 Then
txtScrape.Focus()
txtScrape.SelectionStart = Where - 10
txtScrape.SelectionLength = Where + 50
Result = txtScrape.SelectedText
AllResults = AllResults + Result
Else
AllResults = AllResults + "No Match for: " & item
End If
I recommend that you can split the string into long sentences by special symbols, such as , : ? .
Split(Char[])
You can refer to the following code.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.Text = ""
Dim Index As Integer
Dim longStr() As String
Dim str = TextBox3.Text
longStr = TextBox1.Text.Split(New Char() {CChar(":"), CChar(","), CChar("."), CChar("?"), CChar("!")})
Index = 0
For Each TheStr In longStr
If TheStr.Contains(str) Then
RichTextBox1.AppendText(longStr(Index) & vbCrLf)
End If
Index = Index + 1
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "....."
End Sub
End Class
Result:
Try like this:
Dim ArrStr() As String
Dim Index As Integer
Dim TheStr As String
Dim MatchFound As Boolean
MatchFound = False
ArrStr = Split(txtScrape.text," ")
Index = 1
For Each TheStr In ArrStr
If TheStr = Search Then
Console.WriteLine(Index)
MatchFound = True
End If
Index = Index + 1
Next
Console.WriteLine(MatchFound)
Inside the If statement you will get the index there. And MatchFound is the Boolean value if match found.

Updating values in .csv file depend to values in second .csv

I have two csv files, which contains some data. One of them looks like this:
drid;aid;1date;2date;res;
2121;12;"01.11.2019 06:49";"01.11.2019 19:05";50;
9;10;"01.11.2019 10:47";"01.11.2019 11:33";0;
72;33;"01.11.2019 09:29";"01.11.2019 14:19";0;
777;31;"03.11.2019 04:34";"03.11.2019 20:38";167,35;
Second scv looks like this
datetime;res;drid
"2019-11-01 09:02:00";14,59;2121
"2019-11-03 12:59:00";25,00;777
My target to compare day of date also "drid" and if they are the same in both files then get sum of "res" and replace values of "res" in first csv. Result have to looks like this:
2121;12;"01.11.2019 06:49";"01.11.2019 19:05";64,59;
9;10;"01.11.2019 10:47";"01.11.2019 11:33";0;
72;33;"01.11.2019 09:29";"01.11.2019 14:19";0;
777;31;"03.11.2019 04:34";"03.11.2019 20:38";192,35;
What I have to do to obtain that results in vb.net? I tried to use LINQ Query, but with no results, because I'm newbie and I didn't find way to declare variables in two files and then compare it.
Ok, with .bat I made join both csv in one big.csv and tried to obtain results from same file, but again without success. Last one code is:
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Dim Raplines As String() = IO.File.ReadAllLines("C:\Users\big.csv")
Dim strList As New List(Of String)
Dim readFirst As Boolean
For Each line In Raplines
If readFirst Then
Dim strValues As String() = line.Split(";")
Dim kn1 As String = strValues(0)
Dim kn2 As String = strValues(59)
Dim pvm1 As Date = strValues(2)
Dim pvm1Changed = pvm1.ToString("dd")
Dim pvm2 As Date = strValues(3)
Dim pvm2Changed = pvm2.ToString("dd")
Dim pvm3 As Date = strValues(60)
Dim pvm3Changed = pvm3.ToString("dd")
Dim Las1 As Decimal = strValues(9)
Dim Las2 As Decimal = strValues(61)
Dim sum As Decimal = Las1 - Las2
If kn1 = kn2 And pvm3Changed = pvm1Changed Or pvm3Changed = pvm2Changed Then
strValues(9) = sum
strList.Add(String.Join(";", strValues))
End If
End If
readFirst = True
Next
IO.File.WriteAllLines("C:\Users\big_new.csv", strList.ToArray())
End Sub
Instead of changing the existing file I wrote a new one. I used a StringBuilder so the runtime would not have to create and throw away so many strings. StringBuilder are mutable unlike Strings. I parsed the different formats of the dates and used .Date to disregard the Times.
Private Sub ChangeCVSFile()
Dim lines1 = File.ReadAllLines("C:\Users\someone\Desktop\CSV1.cvs")
Dim lines2 = File.ReadAllLines("C:\Users\someone\Desktop\CSV2.cvs")
Dim sb As New StringBuilder
For Each line1 In lines1
Dim Fields1 = line1.Split(";"c) 'drid;aid;1date;2date;res
For Each line2 In lines2
Dim Fields2 = line2.Split(";"c) 'datetime;res;drid
'
' Trim the exta double quotes "01.11.2019 06:49"
Dim d1 = DateTime.ParseExact(Fields1(2).Trim(Chr(34)), "dd.MM.yyyy hh:mm", CultureInfo.InvariantCulture).Date
' "2019-11-01 09:02:00"
Dim d2 = DateTime.ParseExact(Fields2(0).Trim(Chr(34)), "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture).Date
If Fields1(0) = Fields2(2) AndAlso d1 = d2 Then
Dim sum = CDec(Fields1(4)) + CDec(Fields2(1))
Fields1(4) = sum.ToString
End If
Next
sb.AppendLine(String.Join(";", Fields1))
Next
File.WriteAllText("C:\Users\someone\Desktop\CSV3.cvs", sb.ToString)
End Sub

vb.net how to find a range of digits in string

I would like to split a String by a range of digits (0 to 20) and the letters should be .toLower
How can I define the range in my code?
I have tried to do it like this:("0","1","2","3")
Dim Tolerancevalueofext As String = "JS12"
Dim removenumber As String = Tolerancevalueofext.Substring(0, Tolerancevalueofext.IndexOf("0","1","2","3")).ToLower
But that is definitely wrong.
your request i quite unclear but here is a way to:
1. extract only numbers from string (using Regex).
2. extracting only letters from string that contains digits and converting them to small letters.
Private Sub Example()
Dim Tolerancevalueofext As String = "JS12"
' only numbers, output: "12"
Dim onlynumbers As String = extractNumberFromString(Tolerancevalueofext).ToString()
' only characters, output: "js"
Dim onlycharacters As String = String.Empty
For Each line As String In Tolerancevalueofext
If Not (IsNumeric(line)) Then
onlycharacters += line.ToLower()
End If
Next
End Sub
Public Shared Function extractNumberFromString(ByVal value As String) As Integer
Dim returnVal As String = String.Empty
Dim collection As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(value, "\d+")
For Each m As System.Text.RegularExpressions.Match In collection
returnVal += m.ToString()
Next
Return Convert.ToInt32(returnVal)
End Function
Output: onlynumbers = "12" onlycharacters = "js"

Item pairing between two .txt

I have been trying to combine or pair two text files.
One file contains User:Key
The other file contains Key:Pass
I want a 3rd text file created containing the corresponding pairs of User:Pass based on the key matching.
Here is what Ive tried most recently
Private Sub Rotate()
Dim Cracked() As String = IO.File.ReadAllLines(TextBox1.Text)
For Each lineA In Cracked
TextBox5.Text = lineA
check()
Next
End Sub
Private Sub check()
Dim toCheck() As String = TextBox5.Text.Split(":")
Dim tHash As String = toCheck(0)
Dim tPass As String = toCheck(1)
Dim lines1() As String = IO.File.ReadAllLines(TextBox2.Text)
For Each line In lines1
If lines1.Contains(tHash) Then
Dim toAdd() As String = line.Split(":")
Dim uHash As String = toCheck(0)
Dim uUser As String = toCheck(1)
ListBox1.Items.Add(uUser + ":" + tPass)
End If
Next
End Sub
Public Sub CopyListBoxToClipboard(ByVal ListBox2 As ListBox)
Dim buffer As New StringBuilder
For i As Integer = 0 To ListBox1.Items.Count - 1
buffer.Append(ListBox1.Items(i).ToString)
buffer.Append(vbCrLf)
Next
My.Computer.Clipboard.SetText(buffer.ToString)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
CopyListBoxToClipboard(ListBox1)
End Sub
The delimiter changes but for now the : works.
I tried splitting and matching but either the textbox5 does not rotate or it rotates through the list and thats all.
Something like this?
Dim KeyPassFile As String = "..."
Dim UserKeyFile As String = "..."
Dim UserPassFile As String = "..."
Dim KeyPass As New Hashtable
' Read Key:Pass file
For Each Line In IO.File.ReadAllLines(KeyPassFile)
Dim iStart = Line.IndexOf(":")
Dim Key = Line.Substring(0, iStart)
Dim Pass = Line.Substring(iStart + 1)
KeyPass.Add(Key, Pass)
Next
' Create User:Pass file
Dim OutFile = IO.File.CreateText(UserPassFile)
' Read User:Key file
For Each Line In IO.File.ReadAllLines(UserKeyFile)
Dim iStart = Line.IndexOf(":")
Dim User = Line.Substring(0, iStart)
Dim Key = Line.Substring(iStart + 1)
If KeyPass.ContainsKey(Key) Then
' We have a match for the key, write it to the file
OutFile.WriteLine(User & ":" & KeyPass(Key))
End If
Next
OutFile.Close()
This will probably not work for very large files that doesn't fit in memory, and there is no duplicate check for the key insertion in the hashtable, but I'll leave something for you to do.. :)
Also, in your code, you read the file specified in the TextBox2.Text as many times as there are lines in the TextBox1.Text file..

Using Functions in Visual Basic

The program I'm working on has two different functions, one that calculates the number of syllables in a text file, and another that calculates the readability of the text file based on the formula
206.835-85.6*(Number of Syllables/Number of Words)-1.015*(Number of Words/Number of Sentences)
Here are the problems I'm having:
I'm supposed to display the contents of the text file in a multi-line text box.
I'm supposed to display the answer I get from the function indexCalculation in a label below the text box.
I'm having trouble calling the function to actually have the program calculate the answer to be displayed in the label.
Here is the code I have so far.
Option Strict On
Imports System.IO
Public Class Form1
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Me.Close()
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim open As New OpenFileDialog
open.Filter = "text files |project7.txt|All file |*.*"
open.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
If open.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim selectedFileName As String = System.IO.Path.GetFileName(open.FileName)
If selectedFileName.ToLower = "project7.txt" Then
Dim text As String = File.ReadAllText("Project7.txt")
Dim words = text.Split(" "c)
Dim wordCount As Integer = words.Length
Dim separators As Char() = {"."c, "!"c, "?"c, ":"c}
Dim sentences = text.Split(separators, StringSplitOptions.RemoveEmptyEntries)
Dim sentenceCount As Integer = sentences.Length
Dim vowelCount As Integer = 0
For Each word As String In words
vowelCount += CountSyllables(word)
Next
vowelCount = CountSyllables(text)
Label1.Show(indexCalculation(wordCount, sentenceCount, vowelCount))
Else
MessageBox.Show("You cannot use that file!")
End If
End If
End Sub
Function CountSyllables(word As String) As Integer
word = word.ToLower()
Dim dipthongs = {"oo", "ou", "ie", "oi", "ea", "ee", _
"eu", "ai", "ua", "ue", "au", "io"}
For Each dipthong In dipthongs
word = word.Replace(dipthong, dipthong(0))
Next
Dim vowels = "aeiou"
Dim vowelCount = 0
For Each c In word
If vowels.IndexOf(c) >= 0 Then vowelCount += 1
Next
If vowelCount = 0 Then
vowelCount = 1
End If
Return vowelCount
End Function
Function indexCalculation(ByRef wordCount As Integer, ByRef sentenceCount As Integer, ByRef vowelCount As Integer) As Integer
Dim answer As Integer = CInt(206.835 - 85.6 * (vowelCount / wordCount) - 1.015 * (wordCount / sentenceCount))
Return answer
End Function
End Class
Any suggestions would be greatly appreciated.
Here are my suggestions:
update your indexCalculation function to take in Integers, not strings. that way you don't have to convert them to numbers.
remove all of your extra variables you are not using. this will clean things up a bit.
remove your streamreader. it appears you are reading the text via File.ReadAllText
Label1.Show(answer) should be changed to Label1.Show(indexCalculation(wordCount,sentenceCount,vowelCount)) -- unless Label1 is something other than a regular label, use Label1.Text = indexCalculation(wordCount,sentenceCount,vowelCount))
Then for the vowelCount, you need to do the following:
Dim vowelCount as Integer = 0
For Each word as String in words
vowelCount += CountSyllables(word)
Next
Also, add the logic to the CountSyllables function to make it 1 if 0. If you don't want to include the last character in your vowel counting, then use a for loop instead of a for each loop and stop 1 character short.