In this tutorial I will try to explain how can you use Mid and InStr functions in REALbasic. Learn how can you put the cursor in string where you want and how copy a part of string you are interested in. Watch it, learn it, enjoy it!
Mid Function returns a portion of a string. The first character is numbered 1.
1 | result = Mid(source, start [,length]) |
In this example we will put the cursor on 23 character and copy everything behind him. In result we will get…
1 2 3 | Dim s As String s = Mid("You are learning from REALbasic City", 23) //returns "REALbasic City" |
The next example will make the same but only 9 character behind the cursor position will be copied.
1 2 3 | Dim s As String s = Mid("You are learning from REALbasic City", 23, 9) //returns "REALbasic" |
And this example converts the text string in TextField1 to hex and writes the result to TextField2:
1 2 3 4 5 6 | Dim i as Integer TextField2.text = "" For i = 1 to Len(TextField1.text) TextField2.text = TextField2.text+"&h"+Hex(Asc(Mid(TextField1.text,i,1))) Next |
InStr function returns the position of the first occurrence of a string inside another string. The first character is numbered 1.
1 | result = InStr([start,] source, find) |
This example uses the InStr function to locate a string within another string.
1 2 3 4 5 6 | Dim find As Integer find = InStr("You are learning from REALbasic City", "are") //returns 5 find = InStr("You are learning from REALbasic City", "REAL") //returns 23 find = InStr(5, "You are learning from REALbasic City", "a") //returns 11 find = InStr("You are learning from REALbasic City", "tutspolis") //returns 0 |
This can be fun! We will try now to combine our knowledge and get a string from other random string. It can be static too but this would be too easy… So first the code then the explanation.
1 2 3 4 5 6 | Dim r as New Random Dim data As String data = "My name is Jakub. I'm " + Str(r.InRange(0,60)) + " years old and I like REALbasic" TextArea.text = Mid(data, InStr(data, "I'm") + 3, InStr(data, "years" ) - (InStr(data, "I'm") + 3 ) ) |
If you know what is going now here then bravo if not feel free to read more. In this example we have got a string with random data. It can be for example “My name is Jakub. I’m 27 years old and I like REALbasic”. How can we find and copy the number from this string? As you can see using Mid and InStr functions available in REALbasic.
1 | Str(r.InRange(0,60)) // convert a random number (from 0-60) to string |
Here happens the magic..
1 2 3 | Mid //returns a portion of a string (data, InStr(data, "I'm") + 3, // find in string data text I'm (beginning) and put the cursor 3 character later InStr(data, "years" ) - (InStr(data, "I'm") + 3 ) ) // find in string data text years and select text between I'm and years |