Replace First Occurrance of a substring

W

Wasim Akram

Hi all,

String.Replace replaces all occurrances of a substring in a given string .

Can anyone guide me how can I replace first occurrance of a substring in a
given string.

-
wa
 
O

One Handed Man \( OHM - Terry Burns \)

Use a Regex expression

--

OHM ( Terry Burns )
. . . One-Handed-Man . . .
If U Need My Email ,Ask Me

Time flies when you don't know what you're doing
 
J

Jay B. Harlow [MVP - Outlook]

Wasim,
In addition to the other comments I would do an String.IndexOf along with
String.Remove & String.Insert to manually change the string.

Something like:
Public Shared Function ReplaceFirst(ByVal expression As String, ByVal
find As String, ByVal replacement As String) As String
Dim index As Integer = expression.IndexOf(find)
Return expression.Remove(index, find.Length).Insert(index,
replacement)
End Function

Hope this helps
Jay
 
C

Cor Ligthert

Wasim,

I like those questions where more answers are possible.

\\\
Dim a As String = "terryjaycorherfriedcorjayterry"
Dim b As String = Replace(a, "jay", "jayb", 1, 1)
///

I hope this helps?

Cor
 
J

Jay B. Harlow [MVP - Outlook]

Cor,
Doh!

You know I looked quickly at VB.Replace to get the parameters for mine. I
did not notice (nor remember) the Count (occurances) parameter. I'm sure I
saw count & thought number of characters to look in...

FWIW: You can actually leave the start parameter off.

Dim b As String = Replace(a, "jay", "jayb", , 1)

or

Dim b As String = Replace(a, "jay", "jayb", Count := 1)

Jay
 
C

Cor Ligthert

Jay,

I was writting a funny one using the split, when I remembered me this one,
and would make a message in the kind that Herfried write the replace ones
normally (it was more Armin) and I the strange one, however maybe the OP
would have taken that split one as a real one as once happened and than it
was a problem, so I only provided this Replace one.

For you in pseudo so they will not take it as a right one the splitting one
was, splitting, take the first string, the replacement and than the rest of
the strings() concatinated again from 2 to the end.

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top