How to split string in group in vb.net - vb.net

i'm amol kadam,I want to know how to split string in two part.My string is in Time format (12:12).& I want to seperate this in hour & minute format.the datatype for all variables are string. for hour variable used strTimeHr & for minute strTimeMin .I tried below code but their was a exception "Index and length must refer to a location within the string.
Parameter name: length"
If Not (objDS.Tables(0).Rows(0)("TimeOfAccident") Is Nothing Or objDS.Tables(0).Rows(0)("TimeOfAccident") Is System.DBNull.Value) Then
strTime = objDS.Tables(0).Rows(0)("TimeOfAccident") 'strTime taking value 12:12
index = strTime.IndexOf(":") 'index taking value 2
lastIndex = strTime.Length 'Lastindex taking value 5
strTimeHr = strTime.Substring(0, index) 'strTime taking value 12 correctly
strTimeMin = strTime.Substring(index + 1, lastIndex) 'BUT HERE IS PROBLEM OCCURE strTimeMin Doesn't taking any value
Me.NumUpDwHr.Text = strTimeHr
Me.NumUpDwMin.Text = strTimeMin
End If

The simplest way (assumming that you can ensure the format) is to use a split:
dim strTime as string = objDs.Tables(0).Rows(0).("TimeOfAccident")
dim timeParts() as string = split(strTime,":")
dim strTimeHr as string = timeParts(0)
dim strTimeMn as string = timePartS(1)
you'll also want some error handling to check for formatting and that the split generates the array with at least two elements and what not.
EDIT: After looking more closely at your code, I see the cause of your error.
You have this code:
lastIndex = strTime.Length
strTimeHr = strTime.Substring(0, index)
strTimeMin = strTime.Substring(index + 1, lastIndex)
With that last line giving the error.
The reason that you're getting that error is that strings (and other arrays) in VB.Net are ZERO BASED. Which is why in the strTimeHr field, you're starting at position 0. Length gives you the count, which since the array is zero-based, means the count will be one more than available indexes.
I.e. the last element in a zero based array is the length of the array minus 1.
Therefore, changing your original code to this:
lastIndex = strTime.Length - 1
strTimeHr = strTime.Substring(0, index)
strTimeMin = strTime.Substring(index + 1, lastIndex)
will work as well.

string s = "12:13";
DateTime dt = DateTime.Parse(s);
Console.Write(dt.Hour + " " + dt.Minute);

Try something like (String.Split Method )
Dim str As String = "12:13"
Dim strHr = str.Split(":")(0)
Dim strMin = str.Split(":")(1)

Is the datatype of the column "TimeOfAccident" a DateTime? If so, then the simplest solution would be something like:
'Using LINQ to convert the value to a nullable datetime.
Dim timeOfAccident As Nullable(Of DateTime) = dt.Rows(0).Field(Of Nullable(Of DateTime))("TimeOfAccident")
If timeOfAccident.HasValue Then
Me.NumUpDwHr.Text = timeOfAccident.Hour
Me.NumUpDwMin.Text = timeOfAccident.Minute
End If
If the column "TimeOfAccident" is a string, then you can do something like:
Dim timeOfAccidentString As String = dt.Rows(0).Field(String)("TimeOfAccident")
If Not String.IsNullOrEmpty(timeOfAccidentString) Then
Dim accidentTime As DateTime = DateTime.Parse(timeOfAccidentString)
Me.NumUpDwHr.Text = timeOfAccident.Hour
Me.NumUpDwMin.Text = timeOfAccident.Minute
End If

Related

Substring Method in VB.Net

I have Textboxes Lines:
{ LstScan = 1,100, DrwR2 = 0000000043 }
{ LstScan = 2,200, DrwR2 = 0000000041 }
{ LstScan = 3,300, DrwR2 = 0000000037 }
I should display:
1,100
2,200
3,300
this is a code that I can't bring to a working stage.
Dim data As String = TextBox1.Lines(0)
' Part 1: get the index of a separator with IndexOf.
Dim separator As String = "{ LstScan ="
Dim separatorIndex = data.IndexOf(separator)
' Part 2: see if separator exists.
' ... Get the following part with Substring.
If separatorIndex >= 0 Then
Dim value As String = data.Substring(separatorIndex + separator.Length)
TextBox2.AppendText(vbCrLf & value)
End If
Display as follows:
1,100, DrwR2 = 0000000043 }
This should work:
Function ParseLine(input As String) As String
Const startKey As String = "LstScan = "
Const stopKey As String = ", "
Dim startIndex As String = input.IndexOf(startKey)
Dim length As String = input.IndexOf(stopKey) - startIndex
Return input.SubString(startIndex, length)
End Function
TextBox2.Text = String.Join(vbCrLf, TextBox1.Lines.Select(AddressOf ParseLine))
If I wanted, I could turn that entire thing into a single (messy) line... but this is more readable. If I'm not confident every line in the textbox will match that format, I can also insert a Where() just before the Select().
Your problem is you're using the version of substring that takes from the start index to the end of the string:
"hello world".Substring(3) 'take from 4th character to end of string
lo world
Use the version of substring that takes another number for the length to cut:
"hello world".Substring(3, 5) 'take 5 chars starting from 4th char
lo wo
If your string will vary in length that needs extracting you'll have to run another search (for example, searching for the first occurrence of , after the start character, and subtracting the start index from the newly found index)
Actually, I'd probably use Split for this, because it's clean and easy to read:
Dim data As String = TextBox1.Lines(0)
Dim arr = data.Split()
Dim thing = arr(3)
thing now contains 1,100, and you can use TrimEnd(","c) to remove the final comma
thing = thing.TrimEnd(","c)
You can reduce it to a one-liner:
TextBox1.Lines(0).Split()(3).TrimEnd(","c)

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

Get last number from string and increase it by one

Have some problems with my function. In database i could have diffrent numbers. For instance below: ( i know it looks strange )
12 312323.3
013.43.9
3.23.14353.55 WHATEVER 345.193
728937.3
87.3 ojojo 23.434blabla 24.424.7
What i need to do is increase number after LAST DOT so just make + 1.
The problem is its not working when it comes after dot more than one digit then.
here is my current code:
Dim inputValue as String = "34.234234.6.12"
'--Get Last char from string and add 1 to it
Dim lastChar As String = CInt(CStr(inputValue.Last)) + 1
'--Remove last char and add lastChar
Dim nextCombinNummer As String = lastValue.Nummer.Substring(0, lastValue.Nummer.Length - 1) & lastChar
Return nextCombinNummer
I think the problem is lastValue.Last + 1 as it will take only one digit, and also when i remove by substring last digit but only 2 will be removed.
Can you help me out with this? How to always take number after last dot from string and then increase that number by 1 and return new entire number?
EDIT:
I think i am able to get and increase the number but still dont know how to remove and put it at the end:
Think that's ok:
Dim inputValue as String = "34.234234.6.12"
Dim number As String = inputValue .Substring(inputValue .LastIndexOf("."c) + 1)
Dim numberIncreased as integer = CInt(number) + 1
'How to do this correctly? :
Dim nextCombinNummer As String = lastValue.Nummer.Substring(0, lastValue.Nummer.Length - 1) & numberIncreased
An easy solution is to cast as Integer the last part of the string, add one, then recompose your string :
'Original Value
Dim val As String = "123.456.789"
'We take only the last part and add one
Dim nb = Integer.Parse(val.Substring(val.LastIndexOf(".") + 1)) + 1
'We recompose the string
Dim FinalVal As String = val.Substring(0, val.LastIndexOf(".") + 1) & nb.ToString()
I'd use following which uses String.Split, Int32.TryParse and String.Join:
Dim numbers As New List(Of String) From {"12.312323.3", "013.43.9", "3.231435355345.193", "728937.3", "87.323.43424.424.7"}
for i As Int32 = 0 To numbers.Count -1
Dim num = numbers(i)
Dim token = num.Split("."c)
dim lastNum = token.Last() ' or token(token.Length-1)
Dim n As Int32
If int32.TryParse(lastNum, n)
n += 1
token(token.Length-1) = n.ToString()
End If
numbers(i) = string.Join(".", token)
Next

split string without delimiter and stored in an array using vb.net

The variable datatype is string .it contain string value like greater than 300 chars. i want to split that string by 150 char and stored in the string array using vb.net
My code:
msg = t1("fld_msg")
msg1 = msg.Length
For i = 0 To msg.Length - 1
strarr = msg.Substring(0, 150)
Next
Error:
value of type string cant be converted into one dimensional array
You need a counter to increment the cells in the array
msg = t1("fld_msg")
msg1 = msg.Length
dim Counter as Integer = 0
For i = 0 To msg.Length - 1 Step 150
strarr(Counter) = msg.Substring(i, 150)
Counter += 1
Next
Substring returns a value of type string.
You are trying to put the results into an array.
Try:-
strarr(0) = msg.Substring(0,150)
strarr(1) = msg.Substring(150)
Required correction in your code is to assign substring value to an index of array "strarr(i)" rather than to an array "strarr". Also taking a substring like (0,XX) is not correct. Every time it will return a substring from index 0, use (i*NumberOfCharactersToInclude,XX) instead. But here 'XX' also matters.
For example,
if string has 311 characters and XX is fixed to 150, it will lead to an error in third substring. So i would suggest you to go with this one: (Assuming Framework is 3.5 or above)
For i As Integer = 0 To len ' len represents possible no. of substrings
strarr(i) = New String(msg.Skip(i * 150).Take(150).ToArray)
Next

Substring starting at specific character count

How would you select the last part of a string starting at a specific character count.
For example I would like to get all text after the 3rd comma. but I get an error saying
"StartIndex cannot be less than zero."
Dim testString As String = "part, description, order, get this text, and this text"
Dim result As String = ""
result = testString.Substring(testString.IndexOf(",", 0, 3))
Heres my two cents:
string.Join(",", "aaa,bbb,ccc,ddd,eee".Split(',').Skip(2));
The code "testString.IndexOf(",", 0, 3)" does not find the 3rd comma. It find the first comma starting at position 0 looking at the first 3 positions (i.e. character positions 0,1,2).
If you want the part after the last comma use something like this:
Dim testString As String = "part, description, order, get this text"
Dim result As String = ""
result = testString.Substring(testString.LastIndexOf(",") + 1)
Note the +1 to move to the character after the comma. You should really also find the index first and add checks to confirm that the index is not -1 and index < testString.Length too.
Alternatives(I assume you want all the text after last comma):
Using LastIndexOf:
' You can add code to check if the LastIndexOf returns a positive number
Dim result As String = testString.SubString(testString.LastIndexOf(",")+1)
Regular Expressions:
Dim result As String = Regex.Replace(testString, "(.*,)(.*)$", "$2")
The third argument of indexOf is the number of charcters to search. You are searching for , starting at 0 for 3 characters - that is searching the string par for a comma which does not exist so the returned index is -1, hence your error. I think that you would need to use some recursion:
Dim testString As String = "part, description, order, get this text"
Dim index As Int32 = 0
For i As Int32 = 1 To 3
index = testString.IndexOf(","c, index + 1)
If index < 0 Then
' Not enough commas. Handle this.
End If
Next
Dim result As String = testString.Substring(index + 1)
The IndexOf function only finds the "First" of the specified character. The last parameter (in your case 3) specifies how many characters to examine and not the occurence.
Refer to Find Nth occurrence of a character in a string
The function specified here finds the Nth occurance of a character. Then use the substring function on the occurance returned.
Alternative , you can also use regular expression to find the nth occurance.
public static int NthIndexOf(this string target, string value, int n)
{
Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}");
if (m.Success)
{
return m.Groups[2].Captures[n - 1].Index;
}
else
{
return -1;
}
}
I think this is what you are looking for
Dim testString As String = "part, description, order, get this text"
Dim resultArray As String() = testString.Split(New Char() {","c}, 3)
Dim resultString As String = resultArray(2)