How to insert text into a string at a point of a specific character(s) - vb.net

I have searched the whole internet, and the only things I can find is IndexOf. The issue with that is I need a way to put the insert at a specific one of those chars.
I am currently using this
RichTextBox1.Text = RichTextBox1.Text.Insert(RichTextBox1.Text.Substring(0,RichTextBox1.Text.Split("^")(CurrentSlide).Length), "^")
Which of course is completely incorrect after thinking about it, because the length of the index is not the real length of the text to the index.

I think you have the right idea. It seems like you have a "^" delimited string, and you want to insert an empty at some point. Since a collection is easier to work with than a string, your Split is a good start.
Dim parts = RichTextBox1.Text.Split("^")
Let's make that a list, so we can insert into it:
Dim parts = RichTextBox1.Text.Split("^").ToList()
Now, just insert an empty string where you want the new element:
Dim parts = RichTextBox1.Text.Split("^").ToList()
parts.Insert(CurrentSlide, "")
And combine them back for editing in your textbox:
Dim parts = RichTextBox1.Text.Split("^").ToList()
parts.Insert(CurrentSlide, "")
RichTextBox1.Text = String.Join("^", parts)

Related

My text file lines sometimes contain the same string in vb.net

I have a text file which contains the same string of characters in different lines. I read the file using this code:
Dim readTexte() As String = File.ReadAllLines(OuvrirFichier, Encoding.UTF8)
Dim t As String
For Each t In readTexte
If t.Contains(TreeView1.SelectedNode.Text) Then
TextBox2.Text = Trim(t.Substring(0, 18))
TextBox1.Text = Trim(t.Substring(18, 90))
TextBox4.Text = Trim(t.Substring(107, 120))
End If
Next
However, I have a problem because when cutting and reading these strings. The code is not able to choose the right line to match the TreeView node, because it identifies several equally perfect strings.
For example, the first line contains 3 substrings (fixed width fields):
Saint, Augustine, and Doctor of the Church.
The second line contains three sub-strings as well, slightly different:
Saint, Monica, and mother of Saint Augustine
When I want to read, my code gives me two Augustines, and mixes Augustine and Monique! The TextBox2 contains the string contained in the treeview.
How can I fix this?
The treeview is created as simply as possible, thus:
Dim readText () As String = File.ReadAllLines (OpenFile,
Encoding.UTF8)
Dim s As String
For Each s In readText
TextBox2.Text = Trim (s.Substring (0, 18))
TextBox1.Text = Trim (s.Substring (18, 90))
TextBox4.Text = Trim (s.Substring (107, 120))
Dim node As TreeNode = Me.TreeView1.Nodes (0)
TreeView1.Nodes (0) .Nodes.Add (New TreeNode (TextBox1.Text))
Next
We need to know more about how the TreeView is built before we can answer this. It's possible there is simply not enough data associated with the TreeView right now, and the solution will be in a completely different area of the code.
However, I can provide some notes. First, reading a file is one of the slowest things possible to do in a computer. We already see this is small enough to fit in memory; if it's also reasonably stable (doesn't change often), you can save significant work by loading to the array once when the program starts.
Next, I wouldn't keep just a simple array of strings. Instead, I'd parse the data into separate fields right at load. A Tuple, Class, or even string array can all work.
Finally, this code will continue looping even after if finds a match. I'd have a way to stop once we find what we're looking for.
Put it all together like this:
'Create a set of Tuples. Could also use a class here.
Dim readTexte() As IEnumerable(Of (String, String, String)) =
File.ReadLines(OuvrirFichier, Encoding.UTF8).
Select(Function(line) (Trim(line.SubString(0, 18)), Trim(line.SubString(18,90)), Trim(line.SubString(107,120))) )
'Search the collection for the first match
Dim result = readTexte.First(Function(record) TreeView1.SelectedNode.Text.Equals(record.Item1))
TextBox2.Text = result.Item1
TextBox1.Text = result.Item2
TextBox4.Text = result.Item3
Again, this doesn't solve your matching problem, because the question doesn't contain the information we need to help do that. Please edit the question to include more details on how the TreeView is created.

Formating In Visual Basic

lstPrint.Items.Add(String.Format("{0,-20} {1,5}", "Denomination", "Count"))
For x As Integer = 0 To 6
lstPrint.Items.Add(String.Format("{0,-20} {1,13:S}", ouputArray(x), "Count"))
Next
For the sake of making things easier, Dim outputArray As String() = {"1$", "2$", "5$", "10$", "20$", "50$", "100$"}, and I swapped the second array and made it just say Count.
typically I would simply use Convert.ToChar(Keys.Tab) to make all my columns line up, but I'm trying to get better with string formatting. How would I go about compensating for the difference in characters?
You need to use a fixed-width font if you expect that sort of formatting to produce aligned text. Spaces are much narrower than other characters in variable-width fonts.
Otherwise, how about using a control that actually has columns instead of a ListBox, e.g. ListView or DataGridView? Using the best tool for the job is always a good idea.
I set the font for the list box to a fixed width font. Next I got the length of the longest string in the array. I used .PadLeft to make all the strings the same length.
Private Sub OPCode()
ListBox1.Font = New Font("Consolas", 12)
Dim outputArray As String() = {"1$", "2$", "5$", "10$", "20$", "50$", "100$"}
Dim longest As Integer = outputArray.OrderByDescending(Function(s) s.Length).FirstOrDefault().Length
For Each s In outputArray
ListBox1.Items.Add(s.PadLeft(longest) & " Count")
Next
End Sub
The result:

VB.net get specific characters from listbox

I want to get specific characters from listbox, but I don't know how to do it properly. I already used search (tried because I don't know how properly to name) but get nothing.
So i have this line in my listbox:
1,2014-01-01,Text,Text,XYZ123,Text,Text
How do i need to get only XYZ123? Its always same format, 3 letters and 3 numbers.
Thank you.
I would use a Regular Expression
The Regex of XYZ123 = \w{3}\d{3}
First solution:
Based on a small console application:
Dim i As String = "1,2014-01-01,Text,Text,**XYZ123**,Text,Text"
For Each Str As String In i.Split(",")
Dim match As Match = Regex.Match(Str, "\w{3}\d{3}")
If match.Success Then
Console.WriteLine(Str)
End If
Next
Console.ReadLine()
Second (better) solution:
Based on the comment of Chinz (all credits belong to him)
Dim i As String = "1,2014-01-01,Text,Text,**XYZ123**,Text,Text"
Console.WriteLine(Regex.Match(i, "\w{3}\d{3}").Value)
Console.ReadLine()
if all the strings have the same overall format you could split on "**" and get the [1] from the plitted

Extracting characters from an input string vb.net

Hey guys I'm stuck with this question. Please help.
I want to write a program that can extract alphabetical characters and special characters from an input string. An alphabetical character is any character from "a" to "z"(capital letters and numbers not included") a special character is any other character that is not alphanumerical.
Example:
string = hello//this-is-my-string#capetown
alphanumerical characters = hellothisismystringcapetown
special characters = //---#
Now my question is this:
How do I loop through all the characters?
(the for loop I'm using reads like this for x = 0 to strname.length)...is this correct?
How do I extract characters to a string?
How do I determine special characters?
any input is greatly appreciated.
Thank you very much for your time.
You could loop through each character as follows:
For Each _char As Char In strname
'Code here
Next
or
For x as integer = 0 to strname.length - 1
'Code here
Next
or you can use Regex to replace the values you do not need in your string (I think this may be faster but I am no expert) Take a look at: http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx
Edit
The replacement code will look something as follows although I am not so sure what the regular expression (variable called pattern currently only replacing digits) would be:
Dim pattern As String = "(\d+)?" 'You need to update the regular expression here
Dim input As String = "123//hello//this-is-my-string#capetown"
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, "")
Since you need to keep the values, you'll want to loop through your string. Keeping a list of characters as a result will come in handy since you can build a fresh string later. Then take advantage of a simple Regex test to determine where to place things. The psuedo code looks something like this.
Dim alphaChars As New List(Of String)
Dim specialChars As New List(Of String)
For Each _char As Char in testString
If Regex.IsMatch(_char, "[a-z]")) Then
alphaChars.Add(_char)
Else
specialChars.Add(_char)
End If
Next
Then If you need to dump your results into a full string, you can simply use
String.Join(String.Empty, alphaChars.ToArray())
Note that this code makes the assumption that ANYTHING else than a-z is considered a special character, so if needs be you can do a second regular expression in your else clause to test for you special characters in a similar manner. It really depends on how much control you have over the input.

How can I read individual lines of a CSV file into a string array, to then be selectively displayed via combobox input?

I need your help, guys! :|
I've got myself a CSV file with the following contents:
1,The Compact,1.8GHz,1024MB,160GB,440
2,The Medium,2.4GHz,1024MB,180GB,500
3,The Workhorse,2.4GHz,2048MB,220GB,650
It's a list of computer systems, basically, that the user can purchase.
I need to read this file, line-by-line, into an array. Let's call this array csvline().
The first line of the text file would stored in csvline(0). Line two would be stored in csvline(1). And so on. (I've started with zero because that's where VB starts its arrays). A drop-down list would then enable the user to select 1, 2 or 3 (or however many lines/systems are stored in the file). Upon selecting a number - say, 1 - csvline(0) would be displayed inside a textbox (textbox1, let's say). If 2 was selected, csvline(1) would be displayed, and so on.
It's not the formatting I need help with, though; that's the easy part. I just need someone to help teach me how to read a CSV file line-by-line, putting each line into a string array - csvlines(count) - then increment count by one so that the next line is read into another slot.
So far, I've been able to paste the numbers of each system into an combobox:
Using csvfileparser As New Microsoft.VisualBasic.FileIO.TextFieldParser _
("F:\folder\programname\programname\bin\Debug\systems.csv")
Dim csvalue As String()
csvfileparser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
csvfileparser.Delimiters = New String() {","}
While Not csvfileparser.EndOfData
csvalue = csvfileparser.ReadFields()
combobox1.Items.Add(String.Format("{1}{0}", _
Environment.NewLine, _
csvalue(0)))
End While
End Using
But this only selects individual values. I need to figure out how selecting one of these numbers in the combobox can trigger textbox1 to be appended with just that line (I can handle the formatting, using the string.format stuff). If I try to do this using csvalue = csvtranslator.ReadLine , I get the following error message:
"Error 1 Value of type 'String' cannot be converted to '1-dimensional array of String'."
If I then put it as an array, ie: csvalue() = csvtranslator.ReadLine , I then get a different error message:
"Error 1 Number of indices is less than the number of dimensions of the indexed array."
What's the knack, guys? I've spent hours trying to figure this out.
Please go easy on me - and keep any responses ultra-simple for my newbie brain - I'm very new to all this programming malarkey and just starting out! :)
Structure systemstructure
Dim number As Byte
Dim name As String
Dim procspeed As String
Dim ram As String
Dim harddrive As String
Dim price As Integer
End Structure
Private Sub csvmanagement()
Dim systemspecs As New systemstructure
Using csvparser As New FileIO.TextFieldParser _
("F:\folder\programname\programname\bin\Debug\systems.csv")
Dim csvalue As String()
csvparser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
csvparser.Delimiters = New String() {","}
csvalue = csvparser.ReadFields()
systemspecs.number = csvalue(0)
systemspecs.name = csvalue(1)
systemspecs.procspeed = csvalue(2)
systemspecs.ram = csvalue(3)
systemspecs.harddrive = csvalue(4)
systemspecs.optical = csvalue(5)
systemspecs.graphics = csvalue(6)
systemspecs.audio = csvalue(7)
systemspecs.monitor = csvalue(8)
systemspecs.software = csvalue(9)
systemspecs.price = csvalue(10)
While Not csvparser.EndOfData
csvalue = csvparser.ReadFields()
systemlist.Items.Add(systemspecs)
End While
End Using
End Sub
Edit:
Thanks for your help guys, I've managed to solve the problem now.
It was merely a matter calling loops at the right point in time.
I would recommend using FileHelpers to do the reading.
The binding shouldn't be an issue after that.
Here is the Quickstart for Delimited Records:
Dim engine As New FileHelperEngine(GetType( Customer))
// To Read Use:
Dim res As Customer() = DirectCast(engine.ReadFile("FileIn.txt"), Customer())
// To Write Use:
engine.WriteFile("FileOut.txt", res)
When you get the file read, put it into a normal class and just bind to the class or use the list of items you have to do custom stuff with the combobox. Basically, get it out of the file and into a real class asap, then things will be easier.
At least take a look at the library. After using it, we use a lot more simple flat files since it is so easy, and we haven't written a file access routine since (for that kinda stuff).
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx
I think your main problem is understanding how arrays work (hence the error message).
You can use split and join functions to convert strings into and out of arrays
dim s() as string = split("1,2,3",",") gives and array of strings with 3 elements
dim ss as string = join(s,",") gives you the string back
Firstly, it's actually really good that you are using the TextFieldParser for reading CSV files - most don't but you won't have to worry about extra commas and quoted text etc...
The Readline method only gives you the raw string, hence the "Error 1 Value of type 'String' cannot be converted to '1-dimensional array of String'."
What you may find easier with combo boxes etc is to use an object (e.g. 'systemspecs') rather than strings. Assign the CSV data to the objects and override the "ToString" method of the 'systemspecs' class to display in the combo box how you want with formatting etc. That way when you handle the SelectedIndexChanged event (or similar) you get the "SelectedItem" from the combo box (which can be Nothing so check) and cast it as the 'systemspecs' to use it. The advantage is that you are not restricted to display the exact data in the combo etc.
' in "systemspecs"...
Public Overrides Function ToString() As String
Return Name ' or whatever...
End Function ' ToString
e.g.
dim item as new systemspecs
item.ID = csvalue(1)
item.Name = csvalue(2)
' etc...
combobox1.Items.Add(item)
Let me know if that makes sense!
PK :-)