Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do you get a character in a specific position in a string?

Asked by 6 years ago

Like I have this string

str = "YO MAMA"

So I want to get a character in the position 4 from that string, so I will have the letter M. So how do you do that?

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

Hi, anphu04. There is a built in function called substring in Lua which allows you to get the specific character from a string

There are various ways to get a `substring

The First syntax is `string.sub("Text", startingCharacter, endingCharacter)

Here is an example of the First Syntax

String = "Yo Mama"
print(string.sub(String, 1, 4))

When you print the follow code, you would expect it to print Yo Ma however you see it print Yo M. Well thats because a space is also a character and reads it.

Now onto your question on getting a specific letter. The same rules apply. Except the number changes

the syntax is the same as the above string.sub("Text", startingNumber, endingNumber)

String = "Yo Mama"
print(string.sub(String, 4, 4))

This would result in printing the letter M of the following text. We put in the ending number as 4 because if we do not specify, the code automatically goes to the end of the word. Hence printing out Mama. Since we want it to stop at M we end with the same number. And that is how you manipulate string. Hope you understand. If not, ask question in the comments or look up on wiki linked below.

Global Namespace/String Manipulation Roblox Wiki

Have a lovely day of coding
0
Or you could do String:sub() ee0w 458 — 6y
Ad

Answer this question