How to prepend to a StringBuilder? - vb.net

VB.NET have a method, just like java, to append to an object of type StringBuilder
But can I prepend to this object (I mean a add some string before the stringbuilder value, not after). Here is my code:
'Declare an array
Dim IntegerList() = {24, 12, 34, 42}
Dim ArrayBefore As New StringBuilder()
Dim ArrayAfterRedim As New StringBuilder()
ArrayBefore.Append("{")
For i As Integer = IntegerList.GetLowerBound(0) To IntegerList.GetUpperBound(0)
ArrayBefore.Append(IntegerList(i) & ", ")
Next
' Close the string
ArrayBefore.Append("}")
'Redimension the array (increasing the size by one to five elements)
'ReDim IntegerList(4)
'Redimension the array and preserve its contents
ReDim Preserve IntegerList(4)
' print the new redimesioned array
ArrayAfterRedim.Append("{")
For i As Integer = IntegerList.GetLowerBound(0) To IntegerList.GetUpperBound(0)
ArrayAfterRedim.Append(IntegerList(i) & ", ")
Next
' Close the string
ArrayAfterRedim.Append("}")
' Display the two arrays
lstRandomList.Items.Add("The array before: ")
lstRandomList.Items.Add(ArrayBefore)
lstRandomList.Items.Add("The array after: ")
lstRandomList.Items.Add(ArrayAfterRedim)
If you look at the last 4 lines of my code, I want to add the text just before the string builder all in one line in my list box control. So instead of this:
lstRandomList.Items.Add("The array before: ")
lstRandomList.Items.Add(ArrayBefore)
I want to have something like this:
lstRandomList.Items.Add("The array before: " & ArrayBefore)

You can use StringBuilder.Insert to prepend to the string builder:
Dim sb = New StringBuilder()
sb.Append("World")
sb.Insert(0, "Hello, ")
Console.WriteLine(sb.ToString())
This outputs:
Hello, World
EDIT
Oops, noticed #dbasnett said the same in a comment...

Your code seems like a lot of overkill to use StringBuilder with those For loops.
Why not do this?
Dim IntegerList() = {24, 12, 34, 42}
lstRandomList.Items.Add("The array before: ")
lstRandomList.Items.Add(String.Format("{{{0}}}", String.Join(", ", IntegerList)))
ReDim Preserve IntegerList(4)
lstRandomList.Items.Add("The array after: ")
lstRandomList.Items.Add(String.Format("{{{0}}}", String.Join(", ", IntegerList)))
Job done. Much simpler code.

Related

Loop Through List And Keep Index Count VB.net

How do I irate through a list/array in vb.net and also keep the count of the current item I'm on without having to declare an explicit counter variable?
The result that I am trying to achieve is as follows.
dim i as integer = 0 'evil counter variable
dim arr() as string = {"a","b","c","d","e"}
for each item in arr
console.writeline("Item """ & item & """ is index " & i)
i+=1
next
Without having to declare "i" on its own line
Python has a shorthand way of doing this as follows.
arr=["a","b","c","d","e"]
for i, item in enumerate(arr):
print("Item """ + item + """ is index " + str(i))
A similar implementation in vb.net would be ideal.
edit
The significant part of the code is the enumeration. Not the printing of the values.
Dim arr() As String = {"a", "b", "c", "d", "e"}
For i = 0 To arr.GetUpperBound(0)
Debug.Print($"Item {arr(i)} is index {i}")
Next
The list of possible solutions would not be complete without a Reflection hack, so let's go old school and use an enumerator
Dim arr() As String = {"a", "b", "c", "d", "e"}
Dim enumer As IEnumerator = arr.GetEnumerator
Dim fi As Reflection.FieldInfo = enumer.GetType.GetField("_index", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
While enumer.MoveNext
Dim item As String = DirectCast(enumer.Current, String)
Console.WriteLine($"item: {item} is at index: {fi.GetValue(enumer)}")
End While
A little explanation is needed. arr.GetEnumerator returns a SZArrayEnumerator. This enumerator uses the private field _index to keep track of the array index of the item returned by the Enumerator. The code uses reflection to access the value of _index.
Since this is not a generic Enumerator, the type returned by the Current property is System.Object and needs to be cast back to a String.
As an alternative, you could use string.Join() on a Linq Select():
Console.Write(String.Join(vbCrLf, arr.Select(Function(s, i) "Item " & s & " is Index " & i)))
It's not as good as the Python way, but this will do as you require:
dim arr() as string = {"a","b","c","d","e"}
for i as integer = 0 to arr.length - 1
console.writeline("Item """ & arr(i) & """ is index " & i)
next
Again, not as clean but it does as you need :)

How to get the part inside an "[" and "]" of a string (strange behaviour)

I am trying to get the part of a string between [ and ]. So far I have this:
For Each a As String In CType(TabControl1.SelectedTab.Controls.Item(0),
RichTextBox).Text.Split(System.Environment.NewLine())
If (a.Contains("print ")) Then
Dim sData As String
sData = a.Substring(6)
Dim i, j As Integer
i = sData.IndexOf("[") + "[".Length
j = sData.IndexOf("]") - i
Dim sData1 As String
sData1 = sData.Substring(i, j)
Console.WriteLine(sData1)
End If
Next
However, if I have this:
print [Hello world!]
print [What's up world?]
then the output is this:
Hello world!
but the required output is:
Hello world!
What's up world
I.e. it will not display anything after the first time a print is found.
So why is that happening and how could I fix it?
You are not using Option Strict On which results in you not being told that Split(System.Environment.NewLine()) is truncating the CRLF to CR. The lines of a RichTextBox are separated with LF.
The easy solution would be to use the .Lines property of the RTB:
For Each a As String In CType(TabControl1.SelectedTab.Controls.Item(0), RichTextBox).Lines
U can go with regex but here's a non-regex solution
'U can also use a loop(This is a working solution)
Dim mystring = "print [Hello world]" + Environment.NewLine + "Print [What's up world?]" + ........
For Each line In mystring.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
Dim hloWorld = line.Split("[")(1)
Dim result = hloWorld.Replace("]", "")
Dim finalResult = result + Environment.NewLine
'''Do what u wanna do with ur final result
Next

How could I get the first and last letters from a string?

How can I get my program to take the first and last letters from an entered string?
Example: "I've been told I am a noob!"
Output: "IebntdIaman!"
I tried to use Split with no luck.
Try something like this. since you have a couple of single character words I used a conditional in order to get your desired output. I also am using the String.Split method that removes empty entries in order to prevent a zero length item, then I am taking the result and using the String.Substring Method to parse out your starting and ending chars.
Sub Main()
Dim splitChar As String() = {" "}
Dim example As String = " I've been told I am a noob!"
Dim output As String = ""
Dim result As String() = example.Split(splitChar, StringSplitOptions.RemoveEmptyEntries)
For Each item In result
If item.Length > 1 Then
output += item.Substring(0, 1) & item.Substring(item.Length - 1, 1)
Else
output += item.Substring(0, 1)
End If
Next
Console.WriteLine(output)
Console.ReadLine()
End Sub
This works nicely:
Dim example As String = "I've been told I am a noob!"
Dim result = New String( _
example _
.Split(" "c) _
.SelectMany(Function (w) _
If(w.Count() = 1, _
new Char() { w(0) }, _
New Char() { w.First(), w.Last() })) _
.ToArray())
'IebntdIaman!

How to reverse "This is friday" to "friday is this" in vb.net in Easiest Way

'How to reverse "This is Friday" to "Friday is this" in vb.net in Easiest Way
Dim str As String = txtremarks.Text
Dim arr As New List(Of Char)
arr.AddRange(str.ToCharArray)
arr.Reverse()
Dim a As String = ""
For Each l As Char In arr
a &= l
Next
' I saw on a few forums that to use SPLIT function. Please help
Yes you can use split. You can also use join and the reverse method:
Dim test = "This is Friday"
Dim reversetest = String.Join(" ", test.Split().Reverse)
First you'll want to split your sentence into individual words. This is where you'd use the String.Split method.
Once you have an array containing your individual words, you can reverse that array. Perhaps using Linq's Enumerable.Reverse extension method.
Finally, you can put the words back together into a string. The String.Join method allows you to join the elements of a string array back into a single string.
I'm not a VB programmer, but something like this should work:
Dim str As String = "this is friday"
Dim split As String() = str.Split(" ")
Dim result as String = String.Join(" ", split.Reverse())
Here's a way to do it in 1 line:
Dim reverse As String = "This is friday".Split().Reverse().Aggregate(Function(left, right) String.Join(" ", left, right))
Do note that this has a horrible performance overhead.
Yes, you can Split your String via " " (space) and insert results into array.
Next, read array from the end to start.
Good luck!
Try this...
Dim txt As String = "This is friday"
Dim txtarray() As String = Split(txt.Trim(), " ")
Dim result As String = ""
For x = txtarray.GetUpperBound(0) To 0 Step -1
result += txtarray(x) & " "
Next x
MsgBox(result.Trim())

Help Visual Basic mixing characters

I'm making an application that will change position of two characters in Word.
Imports System.IO
Module Module1
Sub Main()
Dim str As String = File.ReadAllText("File.txt")
Dim str2 As String() = Split(str, " ")
For i As Integer = 0 To str2.Length - 1
Dim arr As Char() = CType(str2(i), Char())
For ia As Integer = 0 To arr.Length() - 1 Step 2
Dim pa As String
pa = arr(ia + 1)
arr(ia + 1) = arr(ia)
arr(ia) = pa
Next ia
For ib As Integer = 0 To arr.Length - 1
Console.Write(arr(ib))
File.WriteAllText("File2.txt", arr(ib))
Next ib
File.WriteAllText("File2.txt", " ")
Console.Write(" ")
Next i
Console.Read()
End Sub
End Module
For example:
Input: ab
Output: ba
Input: asdasd asdasd
Output: saadds saadds
Program works good, it is mixing characters good, but it doesn't write text to the file. It will write text in console, but not in file.
Note: Program is working only with words that are divisible by 2, but it's not a problem.
Also, it does not return any error message.
Your code is overwriting the file that you have already written with a single space (" ") each time round.
You should only open the file once, and append to it using a stream writer:
Using output = File.CreateText("file2.txt")
' Put the for loop here.
End Using
There are some other things wrong with your code. Firstly, use For Each instead of For, this makes your code much more simple and readable. Secondly, try to avoid For loops altogether where possible. For instance, instead of iterating over the characters to output them one at a time, just create a new string from the char array, and write that:
Dim shuffledWord As New String(arr)
output.Write(shuffledWord)
Some of your types are plain wrong, i.e. you are using String in places instead of Char. You should always use Option Strict On. Then the compiler will not tolerate such code.
You should also prefer to use framework methods over VB-specific methods. This makes it easier to understand for C# programmers, and also makes it easier to translate and change (that is, use the Split method of strings instead of a free function, use ToCharArray instead of a cast to Char() …).
Finally, use meaningful variable names. str, str2 and arr are particularly cryptic because they don’t tell the reader of the code anything of interest about the variables.
Sub Main()
Dim text As String = File.ReadAllText("File.txt")
Dim words As String() = str.Split(" "c)
Using output = File.CreateText("file2.txt")
For Each word In words
dim wordChars = word.ToCharArray()
For i As Integer = 0 To wordChars.Length - 1 Step 2
Dim tmp As Char = wordChars(i + 1)
wordChars(i + 1) = wordChars(i)
arr(i) = tmp
Next
Dim shuffledWord As New String(wordChars)
output.Write(shuffledWord + " ")
Console.Write(huffledWord + " ")
Next
End Using
Console.Read()
End Sub