How to get a letter of a string?

The title may be confusing but this example will help, what I’m trying to do, is get a specific letter of a string. Example:

The string: “Hello World!”
What I want: Some way to get “W” from the string without crazy code.

How do I do this?

FUTURE PEOPLE READING THIS:
I meant swap not get

Can you please clarify what you mean?

Are you wanting to find the position of the W?
Are you wanting to remove the W from the string?
Are you trying to determine if W is in the string?

Essentially I’m trying to get the Position of “W” so I can change it.

To get the position, you just do

local Position = string.find("Hello World", "W")

Find wouldn’t work, Hello World is an example and the real string I’m trying to find the position of the letter has multiple 1s and 2s so I need a way to get the specific letter like #1 or #2 of the string.

Sorry for not classifying more on my other reply*

string.find can search for strings in strings

local Position = string.find("as89f7a9827348a7sd89s7a89a#19851", "#1")

but string.find() would find the first target string in a string and return the start and end positions of the target string

are you trying to get the positions of each occurring target string?

I tried testing this and it gave me an error

local Position = string.find("as89f7a9827348a7sd89s7a89a#19851", "#1")

Whats is this string.find("as89f7a9827348a7sd89s7a89a#19851", "#1") finding random codes of alphanumeric characters ,i don’t know about that


Shouldn’t do

Isn’t string.match basically the same as string.find?

I forgot to put the #1 in “” but it gave me nil even though I did the same thing.

string.find finds positions, while string.match searches for a match in a string, returning the match. string.match is more intended for use with the string patterns (the Roblox equivalent of Regex)

1 Like

nil means that what you are searching for was not found in the string

Oh I though it was searching for the position

It is searching for the position. If it can’t find what it is looking for, then there is no position and it returns nil

I’m just gonna give the exact explanation of what I’m trying to do:

I have a DataStore string with “111111111111”
and I wanna change a specific letter/number in the string.
I’m trying to change the 2nd letter in the string so it would turn into 121111111111 keeping all the original values and just changing that “1” into a “2”.

So you just want to change the nth character in a string, regardless of the contents of the string?

Essentially, yes, keep all letters the same and just changing the 2nd letter without effecting the rest.

In that case, you could do something like

local String = "11111111111111111111111" 

local n = 2 -- Position to replace
local ReplaceWith = "2" -- Replace the nth character with this

local Result = string.sub(String, 1, 1) .. ReplaceWith .. string.sub(String, n+1, -1)