How to increase numeric value present in a string - vb.net

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

Related

increment alphanumeric string where alphabet position in a string is keeps changing

I need to save Multiple(about 20-25) serial number of the specimen in my application. Sometimes serial number will be alphanumeric but will be sequential. I need a way out to increment alphanumeric serial numbers based on the first serial number entered.
My main problem is alphabet position and alphabet count keeps changing. Example : 10MG2015 20562MG0 MGX02526 etc etc
I tried but mine works when Alphabet are in starting position and when there are known number of alphabets. Here is my try
Dim intValue as integer
Dim serialno as string
Dim serialno1 as string
For i =0 to 20
Serialno1 = serialno.Substring(3)
Int32.TryParse(Serialno1, intValue)
intValue = intValue + 1
checkedox1.items.add(serialno.Substring(0,3) + intValue.ToString("D3"))
NEXT
Any help is highly appreciated. Thanks in advance
edit 1
Clarity : I want to increment alphanumeric string. Example : If first entered one is 10MG2015 then I should increment to 10MG2016, 10MG2017, 10MG2018, 10MG2019 and so on... For 20562MG0 it will be 20562MG1, 20562MG2 20562MG3 and so on...
Function FindSequenceNumber(SerialNumber As String) As Integer
'Look for at least four digits in a row, and capture all the digits
Dim sequenceExpr As New Regex("([0-9]{4,11})")
Dim result As Integer = -1
Dim m As Match = sequenceExpr.Match(SerialNumber)
If m.Success AndAlso Integer.TryParse(m.Groups(1).Value, result) Then
Return result
Else
'Throw exception, return -1, etc
End If
End Function
See it here:
https://dotnetfiddle.net/gO2nue
Note: the integer type doesn't preserve leading zeros. You may find it better to return a tuple with either the length of the original string, so you can pad zeros to the left if needed to match the original formatting.
Or maybe this:
Function IncrementSerial(SerialNumber As String) As String
'Look for at least four digits in a row, and capture all the digits
Dim sequenceExpr As New Regex("([0-9]{4,11})")
Dim m As Match = sequenceExpr.Match(SerialNumber)
If Not m.Success Then Throw New Exception("No sequence number found")
Dim c = m.Groups(1).Captures(0)
Dim seq = (Integer.Parse(c.Value) + 1).ToString()
If seq.Length < c.Value.Length Then
seq = seq.PadLeft(c.Value.Length, "0"c)
End If
Dim result As String = ""
If c.Index > 0 Then result & = SerialNumber.Substring(0, c.Index)
result &= seq
If c.Index + seq.Length < SerialNumber.Length Then result &= SerialNumber.SubString(c.Index + seq.Length)
Return result
End Function

VB.NET add a decimal Point to Series

The following Function creates multiple series for a graph.
Function createSeries(ByVal fileNames() As String, ByVal intValXAxis As Integer, ByVal intValYAxis As Integer) As Series()
Dim ChartSeries(fileNames.Count) As Series
Dim i As Integer = 0
For Each filename In fileNames
ChartSeries(i) = New Series
ChartSeries(i).ChartType = SeriesChartType.FastLine
ChartSeries(i).ChartArea = "ChartArea1"
If filename.Contains("NOK") = True Then
ChartSeries(i).Color = Color.Red
ChartSeries(i).BorderWidth = 3
Else
ChartSeries(i).Color = Color.Green
End If
Dim fileReader = My.Computer.FileSystem.OpenTextFileReader(filename)
Do
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
ChartSeries(i).Points.AddXY(strCache(intValXAxis - 1), strCache(intValYAxis - 1))
ChartSeries(i).ToolTip = filename
Loop Until fileReader.EndOfStream = True
i += 1
Next
Return ChartSeries
End Function
The problem I have is, that the Y-Values of the Series I create are mostly something like that: 0,09440104 or 0,1757813. I need these Values shown on the graph as they are, but the zero's got removed and the Y-Point-Values are : 9440104 or 1757813
I tried to format them with "Globalization" before adding them to the Series, but it doesn't solved the problem.
Just to be clear: I want the numbers as shown above(0,09440104 and 0,1757813) to be the Y-values of the points.
How can i solve the problem?
Thanks in advance.
By default, En-US culture will read your comma "," as thousand separator and thus taking your data as > 0 rather than < 0.
You have two options: change the culture or change the string format. If all your numbers are less than 1000 (or, to be more precise, not having . as thousand separator), I recommend simply to replace , with .
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
Dim repStrX = strCache(intValXAxis - 1).Replace(",",".")
Dim repStrY = strCache(intValYAxis - 1).Replace(",",".")
ChartSeries(i).Points.AddXY(repStrX , repStrY)
Or, if they are having value more than 1000 (or, again, to be more precise, not having . as thousand separator), without specifying the culture, you could also use Replace with some tricks: making use of non-existing character as intermediate value to flip between . and , in the original string.
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
Dim repStrX = strCache(intValXAxis - 1).Replace(",","G").Replace(".",",").Replace("G",".")
Dim repStrY = strCache(intValYAxis - 1).Replace(",","G").Replace(".",",").Replace("G",".")
ChartSeries(i).Points.AddXY(repStrX , repStrY)

vb.net string contains only 4 digit numbers(or a year)

how can i check if a string only contains 4 digit numbers ( or a year )
i tried this
Dim rgx As New Regex("^/d{4}")
Dim number As String = "0000"
Console.WriteLine(rgx.IsMatch(number)) // true
number = "000a"
Console.WriteLine(rgx.IsMatch(number)) // false
number = "000"
Console.WriteLine(rgx.IsMatch(number)) //false
number = "00000"
Console.WriteLine(rgx.IsMatch(number)) // true <<< :(
this returns false when its less than 4 or at characters but not at more than 4
thanks!
I actually wouldn't use a regex for this. The expression is deceptively simple (^\d{4}$), until you realize that you also need to evaluate that numeric value to determine a valid year range... unless you want years like 0013 or 9015. You're most likely going to want the value as an integer in the end, anyway. Given that, the best validation is probably just to actually try to convert it to an integer right off the bat:
Dim numbers() As String = {"0000", "000a", "000", "00000"}
For Each number As String In numbers
Dim n As Integer
If Integer.TryParse(number, n) AndAlso number.Length = 4 Then
'It's a number. Now look at other criteria
End If
Next
Use LINQ to check if All characters IsDigit:
Dim result As Boolean = ((Not number Is Nothing) AndAlso ((number.Length = 4) AndAlso number.All(Function(c) Char.IsDigit(c))))
You should use the .NET string manipulation functions.
Firstly the requirements, the string must:
Contain exactly four characters, no more, no less;
Must consist of a numeric value
However your aim is to validate a Date:
Function isKnownGoodDate(ByVal input As String) As Boolean 'Define the function and its return value.
Try 'Try..Catch statement (error handling). Means an input with a space (for example ` ` won't cause a crash)
If (IsNumeric(input)) Then 'Checks if the input is a number
If (input.Length = 4) Then
Dim MyDate As String = "#01/01/" + input + "#"
If (IsDate(MyDate)) Then
Return True
End If
End If
End If
Catch
Return False
End Try
End Function
You may experience a warning:
Function isKnownGoodDate does not return a value on all code
paths. Are you missing a Return statement?
this can be safely ignored.

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)

How to split string in group in 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