What is the simplest way to get the second item of each row in a string file - vb.net

I have a String file with 8 items (separated by commas) in each row, e.g., CA,23456,aName,aType,anotherName,aWord,secondword,number. I want to create a new string of items consisting of the 2nd item (an Integer) of each row of the original file. I know there are many ways to do this but someone out there knows how to do it with very few lines of code, which is what I am looking for. I prefer not to use a parser.
The way to show what I have tried is to look at the code below.
Dim sn2 As String = ""
Dim sn2S As String = ""
Using readFile As New StreamReader(newFile1)
Do While readFile.Peek() <> -1
sn2S = readFile.ReadLine(1)
sn2 = sn2 & sn2S & ","
Loop
End Using
The code returns the second character of each row not the second item. What I hope to get is a string that looks like: 123,1345,4325,3321,3456,3211 etc. Where each number is the second item in each row of the original file.

You could split it up by cells
Dim row As String = "CA,23456,aName,aType,anotherName,aWord,secondword,number"
Dim cells() As String = row.Split(",")
Dim cellValue As String = cells(1)
But in your case, I would just do a search and Substring by the index of the delimiter.
Dim startPosition As Integer = row.IndexOf(",") + 1
Dim endPosition As Integer = row.IndexOf(",", startPosition)
Dim cellValue As String = row.Substring(startPosition, endPosition - startPosition)
If you have the whole file in memory, there could be some regex that could do the job with one pass.
As for this line
sn2 = sn2 & sn2S & ","
You might want to check at doing a join or using stringbuilder.

You could try
Dim sn2 As String = ""
Dim sn2S(7) As String = ""
Using readFile As New StreamReader(newFile1)
Do While readFile.Peek() <> -1
Array.Clear(sn25,0,sn25.Length)
sn2S = readFile.ReadLine(1).Split(",")
sn2 = sn2 & sn2S(1) & ","
Loop
End Using

In one line
Dim sn2 = String.Join(",", File.ReadAllLines(newFile1).Select(Function(s) s.Split(","c)(1)))
From the inside-out:
File.ReadAllLines(newFile1) splits the file into lines and results in a string array holding those lines, which is fed into...
...Select(Function(s) s.Split(","c)(1)) which operates on each line by splitting the line by comma s.Split(","c) and then indexing the resulting array (1) to return the second (zero-based) element. This is fed into...
String.Join(",", ... ) which takes those second elements and joins then together with comma.

Related

Extract text in front of a character in certain position

If I have the following string:
100456,3456,1235,0,0,100,500
I need to be able to extract specific values such as 100456, 1235 and 100. I am having trouble writing code to extract text in front of a comma in a certain position.
Basically extract text in front of the 1st comma, extract text in front of the 3rd comma, etc.
Dim fields() As String = Split(TextLine, ",")
For i = 0 To UBound(fields)
If i = 0 Then
Value1 = fields(i)
End If
If i = 3 Then
Value2 = fields(i)
End If
Next
I've tried this, but the loop seems to run more times than it should.
Dim fields() As String = Split(TextLine, ",")
Dim Value1 as String = fields(0)
Dim Value2 as String = fields(2) 'the field in front of 3rd comma is index 2

Concatenating three strings to create one string

I've been working on this assignment for class but ran into an issue when creating a string from three other strings. It creates a invoice number based on the first letter in the first and last name and the last 3 numbers of the zip code.
Dim split As String() = txtName.Text.Split(", ")
Dim last As String = split(0)
Dim first As String = split(1)
Dim invFirst = first.Substring(0, 1)
Dim invLast = last.Substring(0, 1)
Dim invZip = cityState.Substring(cityState.Length - 3)
Dim invNumber = invFirst + invLast + invZip
lstInvoice.Items.Add("Invoice Number: " + invNumber)
Instead of printing out AB123 it will print out just B123. I have tried using + and & and even tired converting all components to a string just to be sure it wasn't trying to treat the values as numbers or something.
Am I missing something like flushing the stream or casting them differently?
Split() returns an array. https://msdn.microsoft.com/library/tabh47cf(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
So you need to trim the strings. And then it will work.
https://dotnetfiddle.net/U5gvh5
Dim split As String() = txtName.Split(",")
Dim last As String = split(0).Trim()
Dim first As String = split(1).Trim()

Input string was not in a correct format while adding string to integer

I have a code like this :
Dim mincatval As String
Dim strarr() As String = dr1(0).ToString().Split(New Char() {"-"c})
Dim i As String
i = (Integer.Parse(strarr(0)) + 1)
mincatval = i
my dr(1) value is L1 i want to add 1,so i want the out put L2,but i am getting error like this :Input string was not in a correct format.
Supposing that strarr(0) is the word "L1" and you want it to become "L2" then you need to isolate the numeric part from the text part and then rebuild the string taking the first part of strarr and the incremented value
Dim mincatval As String
Dim strarr() As String = dr1(0).ToString().Split(New Char() {"-"c})
Dim i As String
Dim itShouldBeAnumber = strarr(0).Substring(1)
if Int32.TryParse(itShouldBeAnumber, i) Then
mincatval = strarr(0).Substring(0,1) & (i + 1)
else
MessageBox.Show("Not a valid number from position 1 of " & strarr(0))
End if
Of course this solution assumes that your string is Always composed of an initial letter followed by a numeric value that could be interpreted as an integer

Replacing string at certain index of Split

Using streamreader to read line by line of a text file. When I get to a certain line (i.e., 123|abc|99999||ded||789), I want to replace ONLY the first empty area with text.
So far, I've been toying with
If sLine.Split("|")(3) = "" Then
'This is where I'm stuck, I want to replace that index with mmm
End If
I want the output to look like this: 123|abc|99999|mmm|ded||789
Considering you already have code determining if the "mmm" string needs to be added or not, you could use the following:
Dim index As Integer = sLine.IndexOf("||")
sLine = sLine.Insert(index + 1, "mmm")
You could split the string, modify the array and rejoin it to recreate the string:
Dim sLine = "123|abc|99999||ded||789"
Dim parts = sLine.Split("|")
If parts(3) = "" Then
parts(3) = "mmm"
sLine = String.Join("|", parts)
End If
I gather that if you find one or more empty elements, you want to replace the first empty element with data and leave the rest blank. You can accomplish this by splitting on the pipe to get an array of strings, iterate through the array and replace the first empty element you come across and exit the loop, and then rejoin your array.
Sub Main()
Dim data As String = "123||abc|99999||ded||789"
Dim parts = data.Split("|")
For index = 0 To parts.Length - 1
If String.IsNullOrEmpty(parts(index)) Then
parts(index) = "mmm"
Exit For
End If
Next
data = String.Join("|", parts)
Console.WriteLine(data)
End Sub
Results:
123|mmm|abc|99999||ded||789

Extract characters from a long string and reformat the output to CSV by using keywords with VB.net

I am new to VB.Net 2008. I have a task to resolve, it is regading extracting characters from a long string to the console, the extracted text shall be reformatted and saved into a CSV file. The string comes out of a database.
It looks something like: UNH+RAM6957+ORDERS:D:96A:UN:EGC103'BGM+38G::ZEW+REQEST6957+9'DTM+Z05:0:805'DTM+137:20100930154
The values are seperated by '.
I can query the database and display the string on the console, but now I need to extract the
Keyword 'ORDERS' for example, and lets say it's following 5 Characters. So the output should look like: ORDERS:D:96A then I need to extract the keyword 'BGM' and its following five characters so the output should look like: BGM+38G:
After extracting all the keywords, the result should be comma seperated and look like:
ORDERS:D:96A,BGM+38G: it should be saved into a CSV file automatically.
I tried already:
'Lookup for containing KeyWords
Dim FoundPosition1 = p_EDI.Contains("ORDERS")
Console.WriteLine(FoundPosition1)
Which gives the starting position of the Keyword.
I tried to trim the whole thing around the keyword "DTM". The EDI variable holds the entire string from the Database:
Dim FoundPosition2 = EDI
FoundPosition2 = Trim(Mid(EDI, InStr(EDI, "DTM")))
Console.WriteLine(FoundPosition2)
Can someone help please?
Thank you in advance!
To illustrate the steps involved:
' Find the position where ORDERS is in the string.'
Dim foundPosition = EDI.IndexOf("ORDERS")
' Start at that position and extract ORDERS + 5 characters = 11 characters in total.'
Dim ordersData = EDI.SubString(foundPosition, 11)
' Find the position where BGM is in the string.'
Dim foundPosition2 = EDI.IndexOf("BGM")
' Start at that position and extract BGM + 5 characters = 8 characters in total.'
Dim bgmData = EDI.SubString(foundPosition2, 8)
' Construct the CVS data.'
Dim cvsData = ordersData & "," & bgmData
I don't have my IDE here, but something like this will work:
dim EDI as string = "UNH+RAM6957+ORDERS:D:96A:UN:EGC103'BGM+38G::ZEW+REQEST6957+9'DTM+Z05:0:805'DTM+137:20100930154"
dim result as string = KeywordPlus(EDI, "ORDER", 5) + "," _
+ KeywordPlus(EDI, "BGM", 5)
function KeywordPlus(s as string, keyword as string, length as integer) as string
dim index as integer = s.IndexOf(keyword)
if index = -1 then return ""
return s.substring(index, keyword.length + length)
end function
for the interrested people among us, I have put the code together, and created
a CSV file out of it. Maybe it can be helpful to others...
If EDI.Contains("LOC") Then
Dim foundPosition1 = EDI.IndexOf("LOC")
' Start at that position and extract ORDERS + 5 characters = 11 characters in total.'
Dim locData = EDI.Substring(foundPosition1, 11)
'Console.WriteLine(locData)
Dim FoundPosition2 = EDI.IndexOf("QTY")
Dim qtyData = EDI.Substring(FoundPosition2, 11)
'Console.WriteLine(qtyData)
' Construct the CSV data.
Dim csvData = locData & "," & qtyData
'Console.WriteLine(csvData)
' Creating the CSV File.
Dim csvFile As String = My.Application.Info.DirectoryPath & "\Test.csv"
Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
outFile.WriteLine(csvData)
outFile.Close()
Console.WriteLine(My.Computer.FileSystem.ReadAllText(csvFile))
End IF
Have fun!