compare a string and trim in vb.net - vb.net

I have this string that shall come in from another file. The string has maximum length of 102 digits. I need to compare the string with numbers in a pair and delete those from that string.
e.g - 6125223659587412563265... till 102
numbers that compare with this string-
first set - 61
new string = 25223659587412563265
second set - 36
new string = 252259587412563265
and so on. the set of numbers shall go to maximum of 51 pairs = 102, which shall give an end result of string = ""
How can i achieve this in a loop?
this is not answer, this is editing the question. i dont know why but the edit button just vaniashed so i have to edit question here.
No duplicates will ever be in this string. and in the end when compares are done, i want to see what numbers are left in pairs.

Dim input As String = "6125223659587412563265"
Dim targets As String() = {"61", "36"}
For Each target As String In targets
input = input.Replace(target, "")
Next
Debug.Assert(input = "252259587412563265")

Here is a simple solution. You will need to add your pairs to the List(Of String) and also initialize input to the string you want to alter.
Dim pairs As New List(Of String)()
Dim input As String = String.Empty
For Each pair As String In pairs
input = input.Replace(pair, String.Empty)
Next

Related

Is it possible to use String.Split() when NewLine is the delimiter?

I have a question which asks me to calculate something from an input file. The problem is, the lines in the file don't use any special character as delimiter, like , or |. I will show it down below.
Data Communication
20
Visual Basic
40
The output I need to write to another file should look like this:
Data communication 20
Visual Basic 40
Total Books : 60
The problem is, how can I specify the delimiter? Like when there is a symbol as in strArray = strLine.Split(","). Since there is nothing I can use as delimiter, how can I split the file content?
There's no real need to split the text in the input file, when you can read a file line by line using standard methods.
You can use, e.g., a StreamReader to read the lines from the source file, check whether the current line is just text or it can be converted to a number, using Integer.TryParse and excluding empty lines.
Here, when the line read is not numeric, it's added as a Key in a Dictionary(Of String, Integer), unless it already exists (to handle duplicate categories in the source file).
If the line represents a number, it's added to the Value corresponding to the category Key previously read, stored in a variable named previousLine.
This setup can handle initial empty lines, empty lines in the text body and duplicate categories, e.g.,
Data Communication
20
Visual Basic
40
C#
100
Visual Basic
10
Other stuff
2
C++
10000
Other stuff
1
If a number is instead found in the first line, it's treated as a category.
Add any other check to handle a different structure of the input file.
Imports System.IO
Imports System.Linq
Dim basePath = "[Path where the input file is stored]"
Dim booksDict = New Dictionary(Of String, Integer)
Dim currentValue As Integer = 0
Dim previousLine As String = String.Empty
Using sr As New StreamReader(Path.Combine(basePath, "Books.txt"))
While sr.Peek > -1
Dim line = sr.ReadLine().Trim()
If Not String.IsNullOrEmpty(line) Then
If Integer.TryParse(line, currentValue) AndAlso (Not String.IsNullOrEmpty(previousLine)) Then
booksDict(previousLine) += currentValue
Else
If Not booksDict.ContainsKey(line) Then
booksDict.Add(line, 0)
End If
End If
End If
previousLine = line
End While
End Using
Now, you have a Dictionary where the Keys represent categories and the related Value is the sum of all books in that category.
You can Select() each KeyValuePair of the Dictionary and transform it into a string that represents the Key and its Value (Category:Number).
Here, also OrderBy() is used, to order the categories alphabetically, in ascending order; it may be useful.
File.WriteAllLines is then called to store the strings generated.
In the end, a new string is appended to the file, using File.AppendAllText, to write the sum of all books in all categories. The Sum() method sums all the Values in the Dictionary.
Dim newFilePath = Path.Combine(basePath, "BooksNew.txt")
File.WriteAllLines(newFilePath, booksDict.
Select(Function(kvp) $"{kvp.Key}:{kvp.Value}").OrderBy(Function(s) s))
File.AppendAllText(newFilePath, vbCrLf & "Total Books: " & booksDict.Sum(Function(kvp) kvp.Value).ToString())
The output is:
C#:100
C++:10000
Data Communication:20
Other stuff:3
Visual Basic:50
Total Books: 10173
Sure.. System.IO.File.ReadAllLines() will read the whole file and split into an array based on newlines, so you'll get an array of 4 elements. You can process it with a flipflop boolean to get alternate lines, or you can try and parse the line to a number and if it works, then its a number and if not, it's a string. If it's a number take the string you remembered (using a variable) from the previous loop
Dim arr = File.ReadALlLines(...)
Dim isStr = True
Dim prevString = ""
For Each s as String in arr
If isStr Then
prevString = s
Else
Console.WriteLine($"The string is {prevString} and the number is {s}")
End If
'flip the boolean
isStr = Not isStr
Next s
I used File.ReadAllLines to get an array containing each line in the file. Since the size of the file could be larger than the sample shown, I am using a StringBuilder. This save having to throw away and create a new string on each iteration of the loop.
I am using interpolated strings indicated by the $ preceding the quotes. This allows you to insert variables into the string surrounded by braces.
Note the Step 2 in the For loop. i will increment by 2 instead of the default 1.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines = File.ReadAllLines("input.txt")
Dim sb As New StringBuilder
Dim total As Integer
For i = 0 To lines.Length - 2 Step 2
sb.AppendLine($"{lines(i)} {lines(i + 1)}")
total += CInt(lines(i + 1))
Next
sb.AppendLine($"Total Books: {total}")
TextBox1.Text = sb.ToString
End Sub

Using Split in Vb.net in last dash

i have two example
"hcg.com.ph?C402-10A-2012-06132017-22"
"hcg.com.?C3032-1B-2012-06132017-1"
output should be
hcg.com.ph?C402-10A-2012-06132017
hcg.com.?C3032-1B-2012-06132017
but i got
hcg.com.ph?C402 and hcg.com.?C3032
Dim FinalSplt() As String
Dim ItemBaseCode As String
FinalSplt = value.ToString.Split("-")
ItemBaseCode = FinalSplt(0)
How to split in the last dash?
Here is some code that uses Substring and LastIndexOf.
'test input
Dim si() As String = {"hcg.com.ph?C402-10A-2012-06132017-22", "hcg.com.?C3032-1B-2012-06132017-1"}
'use to verify
Dim sv() As String = {"hcg.com.ph?C402-10A-2012-06132017", "hcg.com.?C3032-1B-2012-06132017"}
For x As Integer = 0 To si.Length - 1
Dim s As String = si(x).Substring(0, si(x).LastIndexOf("-"c))
'verify
If s = sv(x) Then
Stop 'verified
End If
Next
Ok, without actually writing code I can see you need to split the string more efficiently.
Firstly, strip the quotes.
Secondly, split the string based on the ? mark.
Take the second string in the array, and split that based on the - mark.
Now you have an array of all the portions, join this array with all except the last element.
Join the new string with the original first part.
Add the quotes back if needed.

Parsing through an Array For Next loop Visual Basic

I am stuck here. Spent hours trying many different approaches but nothing is working
I have an array that holds text that looks like this
4456|4450|17
4466|4430|18
4446|4420|19
4436|4410|20
The separator is a pica ("|").
What I am trying to do is run through the array and extract the first two columns in separate strings to compare the values, look for the max, and min.
I am trying to end up with a string like this
4456,4466,4446,4436
Here is the solution:
Dim source As String = prices
Dim stringSeparators() As String = {vbCrLf}
Dim result() As String
result = source.Split(stringSeparators,
StringSplitOptions.RemoveEmptyEntries)
Dim fString As String = String.Join(Of String)(", ", result.Cast(Of String).Select(Of String)(Function(x) x.Split("|")(0)))
MsgBox(fString)
Let's take your example below...
4456|4450|17
4466|4430|18
4446|4420|19
4436|4410|20
prices = [the array shown above]
For Each i As String In prices
high = (i.Split("|"))(0)
highs = highs & highs1 & ","
MsgBox(highs)
Next
The reason you are getting 4,4,5,6,,4,4,5,0,,1,7 is because for each string you are splitting on the | and then taking the first character adding a comma to it.
If you want to get the first column or index whatever you want to call it before the | you need to loop through each string in that array and select out the values...
'this is my test array...
Dim arr As New ArrayList From {"4456|4450|17", "4466|4430|18", "4446|4420|19", "4436|4410|20"}
Now we can use a String.Join function, cast the array for each item as a string and finally select the first item on the split. This will get every item before the | and put them in a string separated with a comma.
Dim fString As String = String.Join(Of String)(", ", arr.Cast(Of String).Select(Of String)(Function(x) x.Split("|")(0)))
If you want the second section select the 1st index as arrays start at 0...
Dim sString As String = String.Join(Of String)(", ", arr.Cast(Of String).Select(Of String)(Function(x) x.Split("|")(1)))
Here is my screenshot of the outputs...

How can I randomly select one of three strings?

I have to create a password and I believe that I can do it, however I am stumped at the very beginning. I have 3 strings of characters, I would like to randomly select one of these three strings. Does anybody know how to do it?
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
So I want to randomly select one of these three strings
I suggest you to use ListOf string instead for this. you can code like the following;
Dim listofStrings As New List(Of String) ' Declaration of list of strings
listofStrings.Add("qwertyuiopasdfghjklzxcvbnm") 'assign values to the list
listofStrings.Add("MNBVCXZLKJHGFDSAPOIUYTREWQ")
listofStrings.Add("1234567890")
Dim rnd As New Random
Dim randomString As String = listofStrings.Item(rnd.Next(0, 3))'select random string from the list
it will generate random numbers between 0 and 2 hence it will help you to select random string from the list of strings based on index referenced by the random number
The below code will help you generate a random number and then pick up the string at that position in the array
string[] arr= {"qwertyuiopasdfghjklzxcvbnm","MNBVCXZLKJHGFDSAPOIUYTREWQ","1234567890"};
Random rnd = new Random();
int cnt = rnd.Next(2);
string r = arr[cnt];

Get the contents of a line in a string

I am using Visual Studio.net, Visual Basic and I have a question.
If I have a string that has many lines in it, what is the best way to get the contents of a certain line?
E.g If the string is as follows:
Public Property TestProperty1 As String
Get
Return _Name
End Get
Set(value As String)
_Name = value
End Set
End Property
What is the best way to get the contents of line 2 ("Get")?
The simplest is to use ElementAtOrdefault since you don't need to check if the collection has so many items. It would return Nothing then:
Dim lines = text.Split({Environment.NewLine}, StringSplitOptions.None)
Dim secondLine = lines.ElementAtOrDefault(1) ' returns Nothing when there are less than two lines
Note that an index is zero-based, hence i have used ElementAtOrDefault(1) to get the second line.
This is the non-linq approach:
Dim secondLine = If(lines.Length >= 2, lines(1), Nothing) ' returns Nothing when there are less than two lines
That depends on what you mean by "best".
The easiest, but least efficient, is to split the string into lines and get one of them:
Dim second As String = text.Split(Environment.NewLine)(1)
The most efficient would be to locate the line breaks in the string and get the line using Substring, but takes a bit more code:
Dim breakLen As Integer = Environment.Newline.Length;
Dim firstBreak As Integer = text.IndexOf(Environment.Newline);
Dim secondBreak As Integer = text.IndexOf(Environment.NewLine, firstBreak + breakLen)
Dim second As String = text.Substring(firstBreak + breakLen, secondBreak - firstBreak - breakLen)
To get any line, and not just the second, you need even more code to loop through the lines until you get to the right one.