473,387 Members | 1,553 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Parsing between a character and sysmbol

I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-" and
stops when it encounters any string character like AF

So my result should be 101.
Any help is appreciated it.

Aug 17 '06 #1
22 1479
Dim x As String = "10AF101-25"
Dim y As String() = x.split("-")
Dim z As String

dim i As Integer
For i = 0 To y(0).length
If IsNumeric(y(i)) Then z = y &= y(i)
Next

<ge*********@gmail.comwrote in message
news:11**********************@75g2000cwc.googlegro ups.com...
>I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-" and
stops when it encounters any string character like AF

So my result should be 101.
Any help is appreciated it.

Aug 17 '06 #2

ge*********@gmail.com wrote:
I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-" and
stops when it encounters any string character like AF

So my result should be 101.
<snip>

The function bellow may help:

Function ScanInt(ByVal T As String) As String
'Finds the position of the "-",
'counting from the last char
Dim P As Integer = T.LastIndexOf("-")

'Scans the text backward until
'a non noumeric item is found
Dim I As Integer
For I = P - 1 To 0 Step -1
If Not Char.IsDigit(T(I)) Then
Exit For
End If
Next

'I is referencing the first non-digit char
I += 1
If I < P Then
Return T.Substring(I, P - I)
Else
Return String.Empty
End If
End Function

Regards,

B.

Aug 17 '06 #3
This seems much more complicated than it need be. Why search for the "-"
when you can immediately split the string at its location and throw away the
part you don't need?

"Branco Medeiros" <br*************@gmail.comwrote in message
news:11**********************@i42g2000cwa.googlegr oups.com...
>
ge*********@gmail.com wrote:
>I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-" and
stops when it encounters any string character like AF

So my result should be 101.
<snip>

The function bellow may help:

Function ScanInt(ByVal T As String) As String
'Finds the position of the "-",
'counting from the last char
Dim P As Integer = T.LastIndexOf("-")

'Scans the text backward until
'a non noumeric item is found
Dim I As Integer
For I = P - 1 To 0 Step -1
If Not Char.IsDigit(T(I)) Then
Exit For
End If
Next

'I is referencing the first non-digit char
I += 1
If I < P Then
Return T.Substring(I, P - I)
Else
Return String.Empty
End If
End Function

Regards,

B.

Aug 17 '06 #4
adm

Scott M. wrote:
This seems much more complicated than it need be.
I think regular expressions might be the way to go here. This kind of
pattern matching is what they are designed for.

To get started, see:
http://www.regular-expressions.info/dotnet.html
http://weblogs.asp.net/rosherove/story/6863.aspx
>
"Branco Medeiros" <br*************@gmail.comwrote in message
news:11**********************@i42g2000cwa.googlegr oups.com...

ge*********@gmail.com wrote:
I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-" and
stops when it encounters any string character like AF

So my result should be 101.
<snip>

The function bellow may help:

Function ScanInt(ByVal T As String) As String
'Finds the position of the "-",
'counting from the last char
Dim P As Integer = T.LastIndexOf("-")

'Scans the text backward until
'a non noumeric item is found
Dim I As Integer
For I = P - 1 To 0 Step -1
If Not Char.IsDigit(T(I)) Then
Exit For
End If
Next

'I is referencing the first non-digit char
I += 1
If I < P Then
Return T.Substring(I, P - I)
Else
Return String.Empty
End If
End Function

Regards,

B.
Aug 17 '06 #5
Hello Scott M.,

There are several things wrong with your code.
First, Using IsNumeric can lead to anomolous results.
Second, your loop bounds are not correct and will cause an exception.
Third, Your loop scans forward, so the result from the example string will
be "10", not the desired "101".

I would have to agree with adm, RegEx is designed specifically for this very
thing. It excels at it.
Grab a copy of Expresso.

-Boo
Dim x As String = "10AF101-25"
Dim y As String() = x.split("-")
Dim z As String
dim i As Integer
For i = 0 To y(0).length
If IsNumeric(y(i)) Then z = y &= y(i)
Next
<ge*********@gmail.comwrote in message
news:11**********************@75g2000cwc.googlegro ups.com...
>I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-"
and stops when it encounters any string character like AF

So my result should be 101.

Any help is appreciated it.

Aug 18 '06 #6

ge*********@gmail.com wrote:
I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-" and
stops when it encounters any string character like AF

So my result should be 101.
Any help is appreciated it.\
Another possible solution :)

Option Strict On
Option Explicit On

Imports System
Imports System.Text.RegularExpressions

Module RegExDemoModule
Private Const DEFAULT_STRING As String = "10AF101-25"
Private Const REGULAR_EXPRESSION As String = "[a-zA-Z]+(\d+)-"

Sub Main()
Dim expression As New Regex(REGULAR_EXPRESSION)
Dim theMatch As Match = expression.Match(DEFAULT_STRING)

Console.WriteLine(theMatch.Groups(1).ToString())
End Sub

End Module

--
Tom Shelton [MVP]

Aug 18 '06 #7

Scott M. wrote:
This seems much more complicated than it need be. Why search for the "-"
when you can immediately split the string at its location and throw away the
part you don't need?
Because split does just that: searches for a pattern. And then allocate
an array. And then populate each member of the array with a copy of the
slice between the separator.

It just bothers me to use Split to do that. Just as IsNumeric: it works
by converting the string to Double, what seems a terrible waste of
processing, to me.

The code seems too much effort but it also seems efficient, to me.
YMMV.

Regards,

Branco.

Aug 18 '06 #8
I would have to agree with adm, RegEx is designed specifically for this
very thing. It excels at it.
Grab a copy of Expresso.
But if you are not used to RegEx can a combination from the code from Scott
and Branco help you.

\\\
Dim x As String = "10AF101-25"
Dim y As String() = x.Split("-"c)
Dim i As Integer
For i = y(0).Length - 1 To 0 Step -1
If Not Char.IsDigit((y(0)(i))) Then
Exit For
End If
Next
MessageBox.Show(y(0).Substring(y(0).Length - 3))
///
Tested of course in this case,

And assuming that there is forever at leaset one hyphen in the value.

:-)

Cor
Aug 18 '06 #9
See my reply too Boo (GhostinAK)
"adm" <ad*****@yahoo.comschreef in bericht
news:11**********************@h48g2000cwc.googlegr oups.com...
>
Scott M. wrote:
>This seems much more complicated than it need be.

I think regular expressions might be the way to go here. This kind of
pattern matching is what they are designed for.

To get started, see:
http://www.regular-expressions.info/dotnet.html
http://weblogs.asp.net/rosherove/story/6863.aspx
>>
"Branco Medeiros" <br*************@gmail.comwrote in message
news:11**********************@i42g2000cwa.googleg roups.com...
>
ge*********@gmail.com wrote:
I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-" and
stops when it encounters any string character like AF

So my result should be 101.
<snip>

The function bellow may help:

Function ScanInt(ByVal T As String) As String
'Finds the position of the "-",
'counting from the last char
Dim P As Integer = T.LastIndexOf("-")

'Scans the text backward until
'a non noumeric item is found
Dim I As Integer
For I = P - 1 To 0 Step -1
If Not Char.IsDigit(T(I)) Then
Exit For
End If
Next

'I is referencing the first non-digit char
I += 1
If I < P Then
Return T.Substring(I, P - I)
Else
Return String.Empty
End If
End Function

Regards,

B.

Aug 18 '06 #10
Doh,

MessageBox.Show(y(0).Substring(y(0).Length - i))

of course,

Cor

"Cor Ligthert [MVP]" <no************@planet.nlschreef in bericht
news:uY**************@TK2MSFTNGP05.phx.gbl...
>I would have to agree with adm, RegEx is designed specifically for this
very thing. It excels at it.
Grab a copy of Expresso.
But if you are not used to RegEx can a combination from the code from
Scott and Branco help you.

\\\
Dim x As String = "10AF101-25"
Dim y As String() = x.Split("-"c)
Dim i As Integer
For i = y(0).Length - 1 To 0 Step -1
If Not Char.IsDigit((y(0)(i))) Then
Exit For
End If
Next
MessageBox.Show(y(0).Substring(y(0).Length - 3))
///
Tested of course in this case,

And assuming that there is forever at leaset one hyphen in the value.

:-)

Cor

Aug 18 '06 #11
Tom Shelton wrote:
ge*********@gmail.com wrote:
>I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-" and
stops when it encounters any string character like AF

So my result should be 101.
Any help is appreciated it.\

Another possible solution :)

Option Strict On
Option Explicit On

Imports System
Imports System.Text.RegularExpressions

Module RegExDemoModule
Private Const DEFAULT_STRING As String = "10AF101-25"
Private Const REGULAR_EXPRESSION As String = "[a-zA-Z]+(\d+)-"

Sub Main()
Dim expression As New Regex(REGULAR_EXPRESSION)
Dim theMatch As Match = expression.Match(DEFAULT_STRING)

Console.WriteLine(theMatch.Groups(1).ToString())
End Sub

End Module
I like this one the best... except for that constants naming convention!
I'm getting COBOL flashbacks! :)

--
Larry Lard
la*******@googlemail.com
The address is real, but unread - please reply to the group
For VB and C# questions - tell us which version
Aug 18 '06 #12
Thanks for everyone help on this. I have tried regex by using this
expression [\d]+-
It almost provides the result that I want except that it brings back
the "-" character also so I get 101- instead of 101.

Any ideas?

Thanks

Aug 18 '06 #13

ge*********@gmail.com wrote:
Thanks for everyone help on this. I have tried regex by using this
expression [\d]+-
It almost provides the result that I want except that it brings back
the "-" character also so I get 101- instead of 101.

Any ideas?

Thanks
(\d+)-

Then, you can get the 101 by referencing element 1 of the groups
collection...

--
Tom Shelton [MVP]

Aug 18 '06 #14

Larry Lard wrote:
Tom Shelton wrote:
ge*********@gmail.com wrote:
I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-" and
stops when it encounters any string character like AF

So my result should be 101.
Any help is appreciated it.\
Another possible solution :)

Option Strict On
Option Explicit On

Imports System
Imports System.Text.RegularExpressions

Module RegExDemoModule
Private Const DEFAULT_STRING As String = "10AF101-25"
Private Const REGULAR_EXPRESSION As String = "[a-zA-Z]+(\d+)-"

Sub Main()
Dim expression As New Regex(REGULAR_EXPRESSION)
Dim theMatch As Match = expression.Match(DEFAULT_STRING)

Console.WriteLine(theMatch.Groups(1).ToString())
End Sub

End Module

I like this one the best... except for that constants naming convention!
I'm getting COBOL flashbacks! :)
Not COBOL fro me, but C/C++. I still have hard time letting that one
go :)

--
Tom Shelton [MVP]

Aug 18 '06 #15
There are several things wrong with your code. First, Using IsNumeric can
lead to anomolous results.
Not when testing single characters it won't. It will only produce
unanticipated results when testing strings of more than 1 charactor in
length.
Second, your loop bounds are not correct and will cause an exception.
True, I forgot to subtract 1 from the upper boundry.
Third, Your loop scans forward, so the result from the example string will
be "10", not the desired "101".
Don't know what you are saying here, the loop will produce: "10101" as
desired.
I would have to agree with adm, RegEx is designed specifically for this
very thing. It excels at it.
I don't disagree, but RegEx is difficult for most who are not accustom to
it.

Here is the corrected code (tested) that works like a charm:

Dim x As String = "10AF101-25"
Dim y As String() = x.Split("-")
Dim z As String = ""

Dim i As Integer
For i = 0 To y(0).Length - 1
If IsNumeric(y(0)(i)) Then z &= y(0)(i)
Next
Grab a copy of Expresso.

-Boo
>Dim x As String = "10AF101-25"
Dim y As String() = x.split("-")
Dim z As String
dim i As Integer
For i = 0 To y(0).length
If IsNumeric(y(i)) Then z = y &= y(i)
Next
<ge*********@gmail.comwrote in message
news:11**********************@75g2000cwc.googlegr oups.com...
>>I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-"
and stops when it encounters any string character like AF

So my result should be 101.

Any help is appreciated it.


Aug 18 '06 #16
Scott M. wrote:
<snip>
Don't know what you are saying here, the loop will produce: "10101" as
desired.
<snip>
Here is the corrected code (tested) that works like a charm:

Dim x As String = "10AF101-25"
Dim y As String() = x.Split("-")
Dim z As String = ""

Dim i As Integer
For i = 0 To y(0).Length - 1
If IsNumeric(y(0)(i)) Then z &= y(0)(i)
Next
<snip>

Notice that the OP asked for the digits that come before the '-' up to
the first non-digit. As the OP points out, in the example string, the
result should be the digits between "10AF" and "-25", i.e., 101.

Your code returns all the numeric chars up to the '-', just
disregarding the intervening letters, that is, 10101, which is wrong.

Even if that was the case, notice that it's not recommended to build a
string like this, but to use a StringBuilder, instead. Also, accessing
array items inside a loop should be avoided whenever possible. If the
OP had asked for all numeric chars before the '-', then a better method
would be:

Function ExtractDigits(Text As String) As String
Dim S As New System.Text.StringBuilder
For Each C As Char in Text
If C = "-"c Then Exit For
If Char.IsDigit(C) Then S.Append(C)
Next
Return S.ToString
End Function

Regards,

Branco.

Aug 19 '06 #17
Scott,

I see now that a single E character can never be an exponent, I did not test
the behaviour of a single plus in this. However to avoid that do I find the
isDigit more describtive and does not even need thinking about the problems
that can be with IsNumeric.

Just my idea,

Cor

"Scott M." <s-***@nospam.nospamschreef in bericht
news:uf****************@TK2MSFTNGP03.phx.gbl...
>There are several things wrong with your code. First, Using IsNumeric
can lead to anomolous results.

Not when testing single characters it won't. It will only produce
unanticipated results when testing strings of more than 1 charactor in
length.
>Second, your loop bounds are not correct and will cause an exception.

True, I forgot to subtract 1 from the upper boundry.
>Third, Your loop scans forward, so the result from the example string
will be "10", not the desired "101".

Don't know what you are saying here, the loop will produce: "10101" as
desired.
>I would have to agree with adm, RegEx is designed specifically for this
very thing. It excels at it.

I don't disagree, but RegEx is difficult for most who are not accustom to
it.

Here is the corrected code (tested) that works like a charm:

Dim x As String = "10AF101-25"
Dim y As String() = x.Split("-")
Dim z As String = ""

Dim i As Integer
For i = 0 To y(0).Length - 1
If IsNumeric(y(0)(i)) Then z &= y(0)(i)
Next
>Grab a copy of Expresso.

-Boo
>>Dim x As String = "10AF101-25"
Dim y As String() = x.split("-")
Dim z As String
dim i As Integer
For i = 0 To y(0).length
If IsNumeric(y(i)) Then z = y &= y(i)
Next
<ge*********@gmail.comwrote in message
news:11**********************@75g2000cwc.googleg roups.com...

I have a string like the following:

10AF101-25

I would like to extract any numerical number that precedes the "-"
and stops when it encounters any string character like AF

So my result should be 101.

Any help is appreciated it.



Aug 19 '06 #18
Notice that the OP asked for the digits that come before the '-' up to
the first non-digit. As the OP points out, in the example string, the
result should be the digits between "10AF" and "-25", i.e., 101.
No, I didn't notice that, but my code could easily be changed to accomodate
that.
Even if that was the case, notice that it's not recommended to build a
string like this, but to use a StringBuilder, instead.
Uh, no that is not true. StringBuilders are very good and I agree that for
large strings and large amounts of manipulations, StringBuilders are
effiient. But no one says strings shouldn't be built manually in all cases.
For small strings and limited amounts of manipulations, manually creating a
string is perfectly fine. In fact, in many cases, because of the intern
pool, there may be no gain in using StringBuilders. And actually, if the
string in question is small, using a StringBuilder may actually use MORE
memory than not using one.
>Also, accessing array items inside a loop should be avoided whenever
possible.
That's ridiculous! Where did you get that from? One of the benefits of
arrays and collections is the ease of iterating through them via loops.
Your code is perfectly fine, but please don't make up best practices just to
bolster your code over others.

If the
OP had asked for all numeric chars before the '-', then a better method
would be:

Function ExtractDigits(Text As String) As String
Dim S As New System.Text.StringBuilder
For Each C As Char in Text
If C = "-"c Then Exit For
If Char.IsDigit(C) Then S.Append(C)
Next
Return S.ToString
End Function

Regards,

Branco.

Aug 19 '06 #19
I don't disagree Cor, but you'll NEVER have a problem checking any single
character with IsNumeric. Only digits will return true. Where you can get
into trouble with IsNumeric is with values that start with a number and then
contain a non-numeric value further down the string like "1024X". But
checking one char at a time is not a problem.
"Cor Ligthert [MVP]" <no************@planet.nlwrote in message
news:%2***************@TK2MSFTNGP05.phx.gbl...
Scott,

I see now that a single E character can never be an exponent, I did not
test the behaviour of a single plus in this. However to avoid that do I
find the isDigit more describtive and does not even need thinking about
the problems that can be with IsNumeric.

Just my idea,

Cor

"Scott M." <s-***@nospam.nospamschreef in bericht
news:uf****************@TK2MSFTNGP03.phx.gbl...
>>There are several things wrong with your code. First, Using IsNumeric
can lead to anomolous results.

Not when testing single characters it won't. It will only produce
unanticipated results when testing strings of more than 1 charactor in
length.
>>Second, your loop bounds are not correct and will cause an exception.

True, I forgot to subtract 1 from the upper boundry.
>>Third, Your loop scans forward, so the result from the example string
will be "10", not the desired "101".

Don't know what you are saying here, the loop will produce: "10101" as
desired.
>>I would have to agree with adm, RegEx is designed specifically for this
very thing. It excels at it.

I don't disagree, but RegEx is difficult for most who are not accustom to
it.

Here is the corrected code (tested) that works like a charm:

Dim x As String = "10AF101-25"
Dim y As String() = x.Split("-")
Dim z As String = ""

Dim i As Integer
For i = 0 To y(0).Length - 1
If IsNumeric(y(0)(i)) Then z &= y(0)(i)
Next
>>Grab a copy of Expresso.

-Boo

Dim x As String = "10AF101-25"
Dim y As String() = x.split("-")
Dim z As String
dim i As Integer
For i = 0 To y(0).length
If IsNumeric(y(i)) Then z = y &= y(i)
Next
<ge*********@gmail.comwrote in message
news:11**********************@75g2000cwc.google groups.com...

I have a string like the following:
>
10AF101-25
>
I would like to extract any numerical number that precedes the "-"
and stops when it encounters any string character like AF
>
So my result should be 101.
>
Any help is appreciated it.
>




Aug 19 '06 #20
I wrote:
Also, accessing array items inside a loop should be avoided whenever
possible.
And then Scott M. wrote:
That's ridiculous! Where did you get that from? One of the benefits of
arrays and collections is the ease of iterating through them via loops.
Your code is perfectly fine, but please don't make up best practices just to
bolster your code over others.
I'm not trying to bolster anything over anyone, just givin' away advise
that I gathered along the road. You're free to accept it or not.

Considering the tone of you message, and knowing that I can really
propose ridiculous things without noticing, I took the time to call
ILDasm on your code. This is what I got inside its main loop (I'm not
even talking about using Split here, that required the conversion of
the "-" char into an array of chars. The things you learn with
ILDasm...):
For i = 0 To y(0).Length - 1
If IsNumeric(y(0)(i)) Then z &= y(0)(i)
; Locates the element Y(0) and pushes it on the stack
IL_002d: ldloc.2
IL_002e: ldc.i4.0
IL_002f: ldelem.ref

; Gets the i-th char from the element
; on the stack (y(0)(i))
IL_0030: ldloc.0 ;
IL_0031: callvirt char String::get_Chars(int32)

; Boxes the char from the previous step and
; calls IsNumeric(Object) (oops!)
IL_0036: box System.Char ;
IL_003b: call bool IsNumeric(object)

;Skips the code if the result of the
;previous step was false
IL_0040: brfalse.s IL_0057

; Pushes z on the stack
IL_0042: ldloc.3

; locates (again!), the element y(0)(i):
; pushes y(0) onto the stack
IL_0043: ldloc.2
IL_0044: ldc.i4.0
IL_0045: ldelem.ref

;gets the i-th char
IL_0046: ldloc.0
IL_0047: callvirt char String::get_Chars(int32)

;Converts it to String (!!!)
IL_004c: call string ToString(char)

; concatenates z and the previous string (creating another string)
; and points z to it
IL_0051: call string String::Concat(string, string)
IL_0056: stloc.3
Next
As you can see, accessing y(0)(i) is somewhat inneficient, because the
code will have to locate the base element by index twice, and the char
by index twice, at every loop. This means locating this element ten
times, for the current example. I guess you'd agree that I can locate
the element only once *outside* the loop, and the given char only once
per cicle (inside the loop). That's exactly what happens when you use
an enumeration on a string, so I really preffer this approach than
accessing an indexed element inside a loop, anytime (unless, of course,
I need the index for something else).

As for the string concatenation, two new strings are created at each
loop cicle, one from the char and one as the result of the
concatenation. To produce your five-chars string you created at least
10 temporary strings. I don't know about you but I don't think this is
efficient at all... Now, I can only guess how the StringBuilder works,
but I'm positive it doesn't use temporary strings, but more likely an
efficient array of chars that will be resized fewer times than you
created strings (if resized at all).

Finally, knowing that IsNumeric() boxes its parameter will really make
me stay far away from it (unless, of course, I need it's VB6 semantics,
which is hardly the case, nowadays).

Hope this clarifies things a bit.

Of course, you can allways argue that the string you're manipulating is
so small that the number of resources and the time taken to proccess it
is negligible, and maybe I'll aggree with you on this. But, who knows,
the OP's example may or may not reflect his actual string. Besides,
there's no information on how many other strings he has to handle.

Best regards,

Branco.

Aug 19 '06 #21
I never claimed that my code was the most efficient way of doing this. What
I did say was that your statement of avoiding arrays inside loops whenever
possible is a ridiculous statement to broadly make. Perhaps it is not the
most efficient way of handling this particular scenario, but, in general,
arrays and collections are prime candidates for iteration via loops. What
makes this particular example less efficient is that there are 2 indexes to
deal with, rather than just the one. In cases where there is just one index
to deal with, or in situations where there are just too many values to write
individual lines of code for, loops are most certainly the way to go with
arrays and collections.

As for the use of StringBuilders, if you read my last response, you must
take into account the base size of a StringBuilder vs. the memory used by
creating new String objects. Again, this particular example may be best
handled with SB's, and I never said SB's were NOT the way to go. What I
said was that because of the intern pool, you can certainly wind up with
situations where using a SB would create more overhead than not using one.

I do agree with your philosophy on advice though, so I hope you don't mind
if I use it:

Just givin' away advice that I gathered along the road. You're free to
accept it or not.

:)
"Branco Medeiros" <br*************@gmail.comwrote in message
news:11**********************@m73g2000cwd.googlegr oups.com...
>I wrote:
>Also, accessing array items inside a loop should be avoided whenever
possible.

And then Scott M. wrote:
>That's ridiculous! Where did you get that from? One of the benefits of
arrays and collections is the ease of iterating through them via loops.
Your code is perfectly fine, but please don't make up best practices just
to
bolster your code over others.

I'm not trying to bolster anything over anyone, just givin' away advise
that I gathered along the road. You're free to accept it or not.

Considering the tone of you message, and knowing that I can really
propose ridiculous things without noticing, I took the time to call
ILDasm on your code. This is what I got inside its main loop (I'm not
even talking about using Split here, that required the conversion of
the "-" char into an array of chars. The things you learn with
ILDasm...):
>For i = 0 To y(0).Length - 1
> If IsNumeric(y(0)(i)) Then z &= y(0)(i)
; Locates the element Y(0) and pushes it on the stack
IL_002d: ldloc.2
IL_002e: ldc.i4.0
IL_002f: ldelem.ref

; Gets the i-th char from the element
; on the stack (y(0)(i))
IL_0030: ldloc.0 ;
IL_0031: callvirt char String::get_Chars(int32)

; Boxes the char from the previous step and
; calls IsNumeric(Object) (oops!)
IL_0036: box System.Char ;
IL_003b: call bool IsNumeric(object)

;Skips the code if the result of the
;previous step was false
IL_0040: brfalse.s IL_0057

; Pushes z on the stack
IL_0042: ldloc.3

; locates (again!), the element y(0)(i):
; pushes y(0) onto the stack
IL_0043: ldloc.2
IL_0044: ldc.i4.0
IL_0045: ldelem.ref

;gets the i-th char
IL_0046: ldloc.0
IL_0047: callvirt char String::get_Chars(int32)

;Converts it to String (!!!)
IL_004c: call string ToString(char)

; concatenates z and the previous string (creating another string)
; and points z to it
IL_0051: call string String::Concat(string, string)
IL_0056: stloc.3
>Next

As you can see, accessing y(0)(i) is somewhat inneficient, because the
code will have to locate the base element by index twice, and the char
by index twice, at every loop. This means locating this element ten
times, for the current example. I guess you'd agree that I can locate
the element only once *outside* the loop, and the given char only once
per cicle (inside the loop). That's exactly what happens when you use
an enumeration on a string, so I really preffer this approach than
accessing an indexed element inside a loop, anytime (unless, of course,
I need the index for something else).

As for the string concatenation, two new strings are created at each
loop cicle, one from the char and one as the result of the
concatenation. To produce your five-chars string you created at least
10 temporary strings. I don't know about you but I don't think this is
efficient at all... Now, I can only guess how the StringBuilder works,
but I'm positive it doesn't use temporary strings, but more likely an
efficient array of chars that will be resized fewer times than you
created strings (if resized at all).

Finally, knowing that IsNumeric() boxes its parameter will really make
me stay far away from it (unless, of course, I need it's VB6 semantics,
which is hardly the case, nowadays).

Hope this clarifies things a bit.

Of course, you can allways argue that the string you're manipulating is
so small that the number of resources and the time taken to proccess it
is negligible, and maybe I'll aggree with you on this. But, who knows,
the OP's example may or may not reflect his actual string. Besides,
there's no information on how many other strings he has to handle.

Best regards,

Branco.

Aug 20 '06 #22
Scott M. wrote:
I never claimed that my code was the most efficient way of doing this. What
I did say was that your statement of avoiding arrays inside loops whenever
possible is a ridiculous statement to broadly make.
I suppose I owe you an apology. I guessed it was clear that I was
refering to your perdulary use of y(0)(i) inside the loop, not the
general issue of "arrays inside loops". This point seemed so basic to
me that needed not an ellaboration and thus the "avoid using array
inside loops" advice, which is clearly misphrased -- and I apologize
for the misunderstanding. My actual point was, if you must access an
array index inside a loop (and, of course, arrays were born to live
inside loops), try at least to minimize the access to the same
elements. Using y(0)(i) twice in the same expression just for the sake
of saving a line of code seems amatteurish to me (in the bad sense),
and, really, not wise. Also, it spells to novices a certain sloppy
style of coding that smells like leaving option strict off, using
Object instead of strong typing, etc.

;-)

Best regards,

Branco.

Aug 20 '06 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Kylotan | last post by:
I have a text file where the fields are delimited in various different ways. For example, strings are terminated with a tilde, numbers are terminated with whitespace, and some identifiers are...
3
by: Fuzzyman | last post by:
I want to parse some text and generate an output that is similar but not identical to the input. The string I produce will be of similar length to the input string - but a bit longer. I'm...
19
by: ARK | last post by:
I am writing a search program in ASP(VBScript). The user can enter keywords and press submit. The user can separate the keywords by spaces and/or commas and key words may contain plain words,...
4
by: Earl | last post by:
I'm curious if there are others who have a better method of accepting/parsing phone numbers. I've used a couple of different techniques that are functional but I can't really say that I'm totally...
1
by: David | last post by:
I have rows of 8 numerical values in a text file that I have to parse. Each value must occupy 10 spaces and can be either a decimal or an integer. // these are valid - each fit in a 10 character...
6
by: Tuomas Rannikko | last post by:
Hello, I'm currently writing a XML processor for the fun of it. There is something I don't understand in the spec though. I'm obviously missing something important. The spec states that both...
2
by: RG | last post by:
I am having trouble parsing the data I need from a Serial Port Buffer. I am sending info to a microcontroller that is being echoed back that I need to remove before I start the actual important...
13
by: Chris Carlen | last post by:
Hi: Having completed enough serial driver code for a TMS320F2812 microcontroller to talk to a terminal, I am now trying different approaches to command interpretation. I have a very simple...
1
by: Sidhartha | last post by:
Hi, I am facing a problem while parsing local language characters using sax parser. We use DOM to parse and SAX to read the source. But when our application parses strings with local language...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.