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

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

Asked by
Loot_O 42
3 years ago
Edited 3 years ago

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

Log in to vote
1
Answered by 3 years ago
Edited 3 years ago

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!

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. incapaz 195 — 3y
0
ok thanks for correcting krowten024nabrU 463 — 3y
0
Thanks! Also, quick question @incapaz, what are type annotations and how are they used? Loot_O 42 — 3y
Ad

Answer this question