Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How would I get a list of certain characters from a string?

Now say for example, I want to get a list of all of the letter A's from "Hello there, how are you? I'm feeling great today." Then I want to replace the A's I got to the letter C so that it would be "Hello there, how cre you? I'm feeling gceat today." Here's something I tried:

function testingFunction(s)
	if type(s) == "string" then
		s:split("a")
	end
end

Thanks!

1 answer

✓ Accepted answer

You can use string.gsub for that. First, it finds all the characters you want in the string and can replace them with another character. For example:

local str = "hallola"

str = str:gsub("a", "o")
print(str) -- will output "hollolo"

And in your case, replacing a with c, this:

function testingFunction(s)
	if type(s) == "string" then
		s = s:gsub("a", "c") -- replace "a" with the character you want to replace, "c" with the replacing character (the character that replaces "a")
		return s -- returns s when you assign a variable to the function (e.g. local str = testingFunction("Hello there, how are you? I'm feeling great today."))
	end
end

Hope this helps!

3 comments

0

Strings are immutable, so you are just returning the same input given with no changes. Do return (s:gsub("a", "c")) to return the new string. Also, use type annotations instead of a typeof check.

0

ok thanks for correcting

0

Thanks! Also, quick question @incapaz, what are type annotations and how are they used?

This discussion is preserved as it was. New answers, comments, and votes are closed.