VBNewLine after certain number of characters AND a given character - vb.net

All,
I developed a formatting/comma-delimiting application that turns a long string of numbers into the correct format for SQL queries.
For example:
101
102
103
104
105
Becomes:
('101','102','103','104','105')
It's a very useful tool, but lets say there are 500 different values to format. This creates a very long line in SQL server.
I've been searching on the internet, but I have yet to find something that can accomplish my question:
How do I word wrap to 100 characters per line, but not breaking up the format:
('Value1','Value2','Value3')
Please let me know if I need to explain further. Thanks for the help!

This will convert the "long string of numbers" into sql format with a lineLength parameter:
Public Function ConvertToSqlParameter(input As String, lineLength As Integer) As String
Dim sb = New StringBuilder("(")
Dim len = 0
For Each s In input.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
If len >= lineLength Then
sb.Append(Environment.NewLine)
len = 0
End If
Dim str = "'" + s + "',"
len += str.Length
sb.Append(str)
Next
sb.Length -= 1
sb.Append(")")
Return sb.ToString()
End Function

Related

VB .NET Convert string to array of bytes without converting the characters

I'm trying to split a string of 32 numerical characters into a 16 length Array of Byte and each value has to stay numerical
from "70033023311330000000004195081460" to array {&H_70, &H_03, &H_30, &H_23, ..}
I've tried multiple stuff but each time either it's the conversion that's wrong or I can't find the appropriate combination of functions to implement it.
'it splits but per 1 character only instead of two
str.Select(Function(n) Convert.ToByte(n, 10)).ToArray
'I also tried looping but then the leading zero disappears and the output is a string converted to HEX which is also not what I want.
Function ConvertStringToHexBinary(str As String) As Byte()
Dim arr(15) As Byte
Dim k = 0
For i As Integer = 0 To str.Length - 1
arr(k) = str(i) & str(i + 1)
k += 1
i += 1
Next
Return arr
End Function
Anyone got any suggestion what to do?
G3nt_M3caj's use of LINQ might be.. er.. appealing to the LINQ lovers but it's horrifically inefficient. LINQ is a hammer; not everything is a nail.
This one is about 3 times faster than the LINQ version:
Dim str As String = "70033023311330000000004195081460"
Dim byt(str.Length/2) as Byte
For i = 0 to str.Length - 1 Step 2
byt(i/2) = Convert.ToByte(str.Substring(i, 2))
Next i
And this one, which does it all with math and doesn't do any new stringing at all is just under 3 times faster than the above (making it around 9 times faster than the LINQ version):
Dim str As String = "70033023311330000000004195081460"
Dim byt(str.Length / 2) As Byte
For i = 0 To str.Length - 1
If i Mod 2 = 0 Then
byt(i / 2) = (Convert.ToByte(str(i)) - &H30) * &HA
Else
byt(i / 2) += Convert.ToByte(str(i)) - &H30
End If
Next i
Of the two, I prefer the stringy version because it's easier to read and work out what's going on - another advantage loops approaches often have over a LINQ approach
Do you need something like this?
Dim str As String = "70033023311330000000004195081460"
Dim mBytes() As Byte = str.
Select(Function(x, n) New With {x, n}).
GroupBy(Function(x) x.n \ 2, Function(x) x.x).
Select(Function(y) Convert.ToByte(New String(y.ToArray()), 10)).ToArray

How to increase numeric value present in a string

I'm using this query in vb.net
Raw_data = Alltext_line.Substring(Alltext_line.IndexOf("R|1"))
and I want to increase R|1 to R|2, R|3 and so on using for loop.
I tried it many ways but getting error
string to double is invalid
any help will be appreciated
You must first extract the number from the string. If the text part ("R") is always separated from the number part by a "|", you can easily separated the two with Split:
Dim Alltext_line = "R|1"
Dim parts = Alltext_line.Split("|"c)
parts is a string array. If this results in two parts, the string has the expected shape and we can try to convert the second part to a number, increase it and then re-create the string using the increased number
Dim n As Integer
If parts.Length = 2 AndAlso Integer.TryParse(parts(1), n) Then
Alltext_line = parts(0) & "|" & (n + 1)
End If
Note that the c in "|"c denotes a Char constant in VB.
An alternate solution that takes advantage of the String type defined as an Array of Chars.
I'm using string.Concat() to patch together the resulting IEnumerable(Of Char) and CInt() to convert the string to an Integer and sum 1 to its value.
Raw_data = "R|151"
Dim Result As String = Raw_data.Substring(0, 2) & (CInt(String.Concat(Raw_data.Skip(2))) + 1).ToString
This, of course, supposes that the source string is directly convertible to an Integer type.
If a value check is instead required, you can use Integer.TryParse() to perform the validation:
Dim ValuePart As String = Raw_data.Substring(2)
Dim Value As Integer = 0
If Integer.TryParse(ValuePart, Value) Then
Raw_data = Raw_data.Substring(0, 2) & (Value + 1).ToString
End If
If the left part can be variable (in size or content), the answer provided by Olivier Jacot-Descombes is covering this scenario already.
Sub IncrVal()
Dim s = "R|1"
For x% = 1 To 10
s = Regex.Replace(s, "[0-9]+", Function(m) Integer.Parse(m.Value) + 1)
Next
End Sub

VB.net incremented number concatenate with texbox value

I'm learning vb.net. I'm trying to create an incremental number that starts at 00000 and concatenate that number with a value from a textbox (eg. JH00001), then insert it into the database.
Please can someone kindly help me with this as I'm totaly new to vb.net.
Thank you all for your assistance in advance. And I'm sorry for my bad English.
Dim number as Integer = 1
Dim text as String = textbox1.text &= number.toString().padLeft(5, "0"c)
Use D5 precision specifier to indicate that the number should be at least 5 digits including leading zeros:
Dim valueFromTextBox As String = "JH"
Dim value As String = ""
For i = 0 To 99
value = valueFromTextBox & i.ToString("D5")
'Insert value to database
Next
Check MSDN for more formatting methods
A for loop should be what you need:
Something like:
Dim text As String = textbox1.text
Dim DBtext As String
For value As Integer = 0 To 5
DBtext = text & value.ToString()
'Insert anything else you need to do. Such as insert into DB.
Next
Just replace the 5 with however many times you need it to run.
I personally prefer using String.Format ...
For i = 0 to 1e6-1
Dim FormattedString = String.Format("{0}{1:00000}", Textbox1.Text, i)
Next

how to find the number of occurrences of a substring within a string vb.net

I have a string (for example: "Hello there. My name is John. I work very hard. Hello there!") and I am trying to find the number of occurrences of the string "hello there". So far, this is the code I have:
Dim input as String = "Hello there. My name is John. I work very hard. Hello there!"
Dim phrase as String = "hello there"
Dim Occurrences As Integer = 0
If input.toLower.Contains(phrase) = True Then
Occurrences = input.Split(phrase).Length
'REM: Do stuff
End If
Unfortunately, what this line of code seems to do is split the string every time it sees the first letter of phrase, in this case, h. So instead of the result Occurrences = 2 that I would hope for, I actually get a much larger number. I know that counting the number of splits in a string is a horrible way to go about doing this, even if I did get the correct answer, so could someone please help me out and provide some assistance?
Yet another idea:
Dim input As String = "Hello there. My name is John. I work very hard. Hello there!"
Dim phrase As String = "Hello there"
Dim Occurrences As Integer = (input.Length - input.Replace(phrase, String.Empty).Length) / phrase.Length
You just need to make sure that phrase.Length > 0.
the best way to do it is this:
Public Function countString(ByVal inputString As String, ByVal stringToBeSearchedInsideTheInputString as String) As Integer
Return System.Text.RegularExpressions.Regex.Split(inputString, stringToBeSearchedInsideTheInputString).Length -1
End Function
str="Thisissumlivinginsumgjhvgsum in the sum bcoz sum ot ih sum"
b= LCase(str)
array1=Split(b,"sum")
l=Ubound(array1)
msgbox l
the output gives u the no. of occurences of a string within another one.
You can create a Do Until loop that stops once an integer variable equals the length of the string you're checking. If the phrase exists, increment your occurences and add the length of the phrase plus the position in which it is found to the cursor variable. If the phrase can not be found, you are done searching (no more results), so set it to the length of the target string. To not count the same occurance more than once, check only from the cursor to the length of the target string in the Loop (strCheckThisString).
Dim input As String = "hello there. this is a test. hello there hello there!"
Dim phrase As String = "hello there"
Dim Occurrences As Integer = 0
Dim intCursor As Integer = 0
Do Until intCursor >= input.Length
Dim strCheckThisString As String = Mid(LCase(input), intCursor + 1, (Len(input) - intCursor))
Dim intPlaceOfPhrase As Integer = InStr(strCheckThisString, phrase)
If intPlaceOfPhrase > 0 Then
Occurrences += 1
intCursor += (intPlaceOfPhrase + Len(phrase) - 1)
Else
intCursor = input.Length
End If
Loop
You just have to change the input of the split function into a string array and then delare the StringSplitOptions.
Try out this line of code:
Occurrences = input.Split({phrase}, StringSplitOptions.None).Length
I haven't checked this, but I'm thinking you'll also have to account for the fact that occurrences would be too high due to the fact that you're splitting using your string and not actually counting how many times it is in the string, so I think Occurrences = Occurrences - 1
Hope this helps
You could create a recursive function using IndexOf. Passing the string to be searched and the string to locate, each recursion increments a Counter and sets the StartIndex to +1 the last found index, until the search string is no longer found. Function will require optional parameters Starting Position and Counter passed by reference:
Function InStrCount(ByVal SourceString As String, _
ByVal SearchString As String, _
Optional ByRef StartPos As Integer = 0, _
Optional ByRef Count As Integer = 0) As Integer
If SourceString.IndexOf(SearchString, StartPos) > -1 Then
Count += 1
InStrCount(SourceString, _
SearchString, _
SourceString.IndexOf(SearchString, StartPos) + 1, _
Count)
End If
Return Count
End Function
Call function by passing string to search and string to locate and, optionally, start position:
Dim input As String = "Hello there. My name is John. I work very hard. Hello there!"
Dim phrase As String = "hello there"
Dim Occurrences As Integer
Occurrances = InStrCount(input.ToLower, phrase.ToLower)
Note the use of .ToLower, which is used to ignore case in your comparison. Do not include this directive if you do wish comparison to be case specific.
One more solution based on InStr(i, str, substr) function (searching substr in str starting from i position, more info about InStr()):
Function findOccurancesCount(baseString, subString)
occurancesCount = 0
i = 1
Do
foundPosition = InStr(i, baseString, subString) 'searching from i position
If foundPosition > 0 Then 'substring is found at foundPosition index
occurancesCount = occurancesCount + 1 'count this occurance
i = foundPosition + 1 'searching from i+1 on the next cycle
End If
Loop While foundPosition <> 0
findOccurancesCount = occurancesCount
End Function
As soon as there is no substring found (InStr returns 0, instead of found substring position in base string), searching is over and occurances count is returned.
Looking at your original attempt, I have found that this should do the trick as "Split" creates an array.
Occurrences = input.split(phrase).ubound
This is CaSe sensitive, so in your case the phrase should equal "Hello there", as there is no "hello there" in the input
Expanding on Sumit Kumar's simple solution, here it is as a one-line working function:
Public Function fnStrCnt(ByVal str As String, ByVal substr As String) As Integer
fnStrCnt = UBound(Split(LCase(str), substr))
End Function
Demo:
Sub testit()
Dim thePhrase
thePhrase = "Once upon a midnight dreary while a man was in a house in the usa."
If fnStrCnt(thePhrase, " a ") > 1 Then
MsgBox "Found " & fnStrCnt(thePhrase, " a ") & " occurrences."
End If
End Sub 'testit()
I don't know if this is more obvious?
Starting from the beginning of longString check the next characters up to the number characters in phrase, if phrase is not found start looking from the second character etc. If it is found start agin from the current position plus the number of characters in phrase and increment the value of occurences
Module Module1
Sub Main()
Dim longString As String = "Hello there. My name is John. I work very hard. Hello there! Hello therehello there"
Dim phrase As String = "hello There"
Dim occurences As Integer = 0
Dim n As Integer = 0
Do Until n >= longString.Length - (phrase.Length - 1)
If longString.ToLower.Substring(n, phrase.Length).Contains(phrase.ToLower) Then
occurences += 1
n = n + (phrase.Length - 1)
End If
n += 1
Loop
Console.WriteLine(occurences)
End Sub
End Module
I used this in Vbscript, You can convert the same to VB.net as well
Dim str, strToFind
str = "sdfsdf:sdsdgs::"
strToFind = ":"
MsgBox GetNoOfOccurranceOf( strToFind, str)
Function GetNoOfOccurranceOf(ByVal subStringToFind As String, ByVal strReference As String)
Dim iTotalLength, newString, iTotalOccCount
iTotalLength = Len(strReference)
newString = Replace(strReference, subStringToFind, "")
iTotalOccCount = iTotalLength - Len(newString)
GetNoOfOccurranceOf = iTotalOccCount
End Function
I know this thread is really old, but I got another solution too:
Function countOccurencesOf(needle As String, s As String)
Dim count As Integer = 0
For i As Integer = 0 to s.Length - 1
If s.Substring(i).Startswith(needle) Then
count = count + 1
End If
Next
Return count
End Function

How do you convert a string into hexadecimal in VB.NET?

How do I convert a string from a textbox into hexadecimal?
I have only found ways in C#. Does VB.NET have the ability to do such a thing? If it can then I'd like to know how to convert string to hex and hex to string.
Dim val As String
val = "10"
Dim hexVal As Integer
hexVal = Convert.ToInt32(val, 16) //16 specifies the base
Console.WriteLine(hexVal)
This will display 16 which is the integer equivalent of the hexadecimal string "10".
You can convert an integer to a hexdecimal number easily by doing:
Convert.ToInt32(15, 16)
And to convert it back to an integer, you can do:
Integer.Parse("15f", System.Globalization.NumberStyles.HexNumber)
Public Function StrToHex(ByRef Data As String) As String
Dim sVal As String
Dim sHex As String = ""
While Data.Length > 0
sVal = Conversion.Hex(Strings.Asc(Data.Substring(0, 1).ToString()))
Data = Data.Substring(1, Data.Length - 1)
sHex = sHex & sVal
End While
Return sHex
End Function
Tried and tested code
Create this function by copy pasting it.
Function StringToHex(ByVal text As String) As String
Dim hex As String
For i As Integer = 0 To text.Length - 1
hex &= Asc(text.Substring(i, 1)).ToString("x").ToUpper
Next
Return hex
End Function
Use it like this
Debug.WriteLine(StringToHex("sim0n"))
Source
To convert into hexadecimal, use Convert.ToInt32(val, 16). Convert.ToInt32 supports limited bases, 2, 8, 10, and 16.
To convert into any base, use:
Public Shared Function IntToString(value As Integer, baseChars As Char()) As String
Dim result As String = String.Empty
Dim targetBase As Integer = baseChars.Length
Do
result = baseChars(value Mod targetBase) + result
value = value / targetBase
Loop While value > 0
Return result
End Function
The above function comes from this question. The C# to VB conversion was done using this.
Short and effective expression to display all characters of String s in hexadecimal form can be written using LINQ:
String.Join(" ", s.Select(Function(c) Conversion.Hex(AscW(c)).PadLeft(4, "0")).ToArray()))
Example:
For string ► fix it gives string 25BA 0020 0066 0069 0078.
Enjoy!
Please keep in mind this is Unicode-enabled, returning 4-digit hexadecimal value for every character, because old plain Non-Unicode ASCII is dead and you should no longer rely on it in any application.
In my humble opinion the code of Tilak seems OK, but is not.
The rounding of value / targetBase gives results that are too large.
By using Fix() the resulting integers will be as they should be.
I compliment Tilak for finding such a neat solution for the question.
In the accompanying code I will show how functions like IntToString can be tested easily.
The expected message in the message box is:
The old results are;
0 1 10 101 100 101 1010 1001 1000 1001 1010
0 1 1X 10 11 1XX 1X0 1X1 10X 100 101
0 1 X 1y 10 11 XX Xy X0 X1 XX
0 1 X 1y 1z 10 11 1X Xy Xz X0
The new results are;
0 1 10 11 100 101 110 111 1000 1001 1010
0 1 X 10 11 1X X0 X1 XX 100 101
0 1 X y 10 11 1X 1y X0 X1 XX
0 1 X y z 10 11 1X 1y 1z X0
The new results are better IMHO.
Public Sub test()
Dim numberCharacters As String = "01Xyz"
Dim messageText As String = "The old results are;" & vbNewLine
For loopCount As Integer = 1 To 2
If loopCount = 2 Then messageText &= "The new results are;" & vbNewLine
For baseLength As Integer = 2 To 5
Dim baseCharacters As Char() = _
Strings.Left(numberCharacters, baseLength).ToArray
For integerValue As Integer = 0 To 10
Dim resultText As String = _
Me.IntToString(integerValue, baseCharacters, loopCount = 2)
messageText &= resultText & " "
Next
messageText &= vbNewLine
Next
Next
Call MsgBox(berichtTekst & "The new results are better IMHO.")
End Sub
Public Function IntToString(value As Integer, baseChars As Char(), _
Optional newCode As Boolean = False) As String
Dim result As String = String.Empty
Dim targetBase As Integer = baseChars.Length
Do
result = baseChars(value Mod targetBase) & result
If newCode Then ' Improved code
value = Fix(value / targetBase)
Else ' Original code
value = value / targetBase
End If
Loop While value > 0
Return result
End Function
Hopefully this will help others.
I have more than 25 years experience as a programmer, mainly in RPG, Cobol, Synon, CL and Basic. I also know some Delphi, Pascal and C#. I am sure I can be a help to this community.
It makes me sad that I cannot comment to answers. Hopefully someone will add me some points, so that I can more easily help others from now on.
Because of this I add my comment to the answer of Tilak, dated may 8, 2012, as an answer. This is the first and hopefully the only time that I resort to this. Sorry for that, but I know no other way.