Reputation: 1085
I'm trying to use InStr to find the first character that isn't a "0" (starting from the left-hand side) in strings like this:
000000000001
000000004092
000000000052
000000001006
Can this be done with InStr, or should I use something different?
Upvotes: 2
Views: 1744
Reputation: 726609
If you are looking for an index of an item that is not zero (that may also be a non-digit) use this regular expression: [^0]
Dim pos as Integer = Regex.Match(str, "[^0]").Index
Keep in mind, Regex functions require the following library call:
Imports System.Text.RegularExpressions
This will not work well when the string is composed entirely of zeros, so you may want to modify the expression to allow zero to be the last (or the only) character in the string:
`([^0])|(0$)`
^--- This meta-character matches an end-of-string marker
Upvotes: 4
Reputation: 460138
If you're using VB.NET you should use .NET methods.
One way is using Enumerable.Where
which is a Linq
method:
Dim value = "000000000001"
Dim firstNotZero = From c In value Where c <> "0"c
If firstNotZero.Any Then
Dim first As Char = firstNotZero.First
End If
Edit: If you don't want to use Linq or Regex, you can also use a simple loop:
Dim lines = {"000000000001", "000000004092", "000000000052", "000000001006"}
Dim firstDigits As New List(Of Char)
For Each line In lines
For Each c In line
If c <> "0"c Then
firstDigits.Add(c)
Exit For
End If
Next
Next
This adds all first not 0 characters to a List(Of Char)
.
Upvotes: 2
Reputation: 499042
There is no way to "negate" the parameters of InStr
.
If you know the input, you can simply search for what should not there (possibly using regex).
It is difficult to give you something less general as an answer without details such as - what is the range of input characters? What rules govern a match? How is this to be used?
Upvotes: 0