Julianna Gajraj
Julianna Gajraj

Reputation: 11

How do you replace the first certain character in a string leaving the second character the same

I just need to know how to replace a the first certain character that appears in a string with a different character.

For example, I need to be able to change "need" to "noed" leaving the second 'e' the same.

What I have right now is changing "need" to "nood"

If you need any clarification please just ask me! Thank you so much!

Upvotes: 1

Views: 44

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

Use IndexOf() to find the position of the "e". Now Insert() the "o" at that position and Remove() the position immediately following that to remove the "e":

    Dim word As String = "need"
    Dim oldLetter As String = "e"
    Dim newLetter As String = "o"
    Dim index As Integer = word.IndexOf(oldLetter)
    If index <> -1 Then
        word = word.Insert(index, newLetter).Remove(index + 1, 1)
    End If

Upvotes: 1

F0r3v3r-A-N00b
F0r3v3r-A-N00b

Reputation: 3003

    Dim findWhat As String = "ee"
    Dim searchThis As String = "need"
    Dim replaceWith As String = "o"
    Dim result As String = searchThis.Replace(findWhat, replaceWith & findWhat.Substring(1))
    Console.WriteLine(result)

Upvotes: 0

Related Questions