IndexOf string method

  • Thread starter Thread starter sh
  • Start date Start date
S

sh

The IndexOf string method returns the position of the first occurrence
of a character in a string. Is there a method to find the x occurrence
of a character, for example, the 28th occurrence of a character in a string?

Thanks
 
Shamanda,

I don't know if you are the same as gonzosez where is asked almost the same
question in the second message after yours.

\\\
dim mystring as string = "I contain 70 characters"
if mystring.length > 27 then
dim TwentyEightchar = mystring(27)
end if
///
I hope this helps,

Cor
 
Won't that give me what the 27th character is? I'm looking for the
position of the 27th occurrence of some character. For example

MyString = "12x34x56x78x90x12x34x56x78x90x"

So the position of the 7th occurrence of x is 21 (or 20 if zero based)
 
Cor said:
\\\
dim mystring as string = "I contain 70 characters"
if mystring.length > 27 then
dim TwentyEightchar = mystring(27)
end if
///

Cor, you've missed what he wants to achieve. He wants to find the 28th
occurrence of a substring within a string.

One possible method (watch for typos):

Public Function FindNthOccurrence(source As String, substring As
String, occurrence As Integer) As Integer
Dim index As Integer = -1
For i As Integer = 0 to occurrence - 1
index = source.IndexOf(substring, index + 1)
If index = -1 Then
Exit For
End If
Next

Return index
End Function
 
Oh,

That is not to be done simple, you can use repeatly an indexof char, which
is many times quicker than a indexof from a string but you would have to
build code for that something as beneath not really tested see it as pseudo

\\\
dim mychar as char = "x"c
dim start as integer = 0
for x = 0 to 6
if start < mystring.lenth
start = mystring.indexof(start, mychar)
else
exit for
end if
next
///

I hope this helps,

Cor
 
Back
Top