viernes, 11 de octubre de 2013

Search characters into a string in Visual Basic



Since time ago I wanted to Post this entry because sometimes we want to read substrings in a main string. Of course obviously such tool doesn’t exist therefore we must create it.
Microsoft provides one tool and it is the following:

Dim text As String = "I have been playing tennis since I was a child"
Dim character As String = "I was a child"
Dim number As Integer

number = InStr(1,text, character, CompareMethod.Binary)

In this case when we want to know which is the position than one substring these code back to us the position where these. This code is amazing because you can search a string and not character, in this case when I want to search “I was a child” into “I have been playing tennis since I was a child”, this back to us the position where begin “I was a child” than is 34.

I want to show one example:

We suppose that I want to modify “I was a child” and then put “I was 19” in the main string, like this:
“I have been playing since I was 19”


Well it’s easy to resolve because we know the method and this is the following:

Dim text As String = "I have been playing tennis since I was a child"
Dim character As String = "I was a child"
Dim number As Integer

number = InStr(1,text, character, CompareMethod.Binary)

text = text.remove(number-1,13)'Add -1 because visual basic remove the text one position before the text which we want to remove.

replace(text, " ", "")'remove all spaces

text = text & "I was 19"

'We will see: “I have been playing since I was 19"

No hay comentarios:

Publicar un comentario