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

Is there an easier way to manipulate a string to get what I want out of it?

Asked by 6 years ago

Here is my code:

local function firstLetter(str)

    return string.sub(str, 1, 1)

end

local function lastLetter(str)

    return string.sub(str, -1)

end

local function middleLetters(str)

    return string.sub(str, 2, -2)

end

local str = "Happy Forever!"

print(firstLetter(str))
print(lastLetter(str))
print(middleLetters(str))

I was wondering if there is a better/easier method to getting what I need, and if I am even doing this correctly in the first place. I hope you guys can help. Thanks!

0
In terms of efficiency, `middleLetters` isn't a great function to use in palindrome-testing. That's because it needs to copy the entire middle section, making the resulting code O(n^2) which is *extremely* slow for long strings (e.g., 1000s or 10s of thousands of characters) BlueTaslem 18071 — 6y

1 answer

Log in to vote
4
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
6 years ago

You're doing this right. string.sub is the right way to get pieces of a string.

As a convenience, you can use a different syntax.

Instead of string.sub(str, -1), you can say str:sub(-1).

The same goes for the other uses: string.sub(str, 1, 1) can become str:sub(1, 1).


Is there a particular thing you don't like about your approach that you hope you can do better? How is this being used?

0
string.sub(str) is just syntax sugar for str:sub() User#19524 175 — 6y
2
and it can greatly improve readability by reducing the noise of `string` everywhere and putting a verb between the string you're acting on and the parameters of the method BlueTaslem 18071 — 6y
0
I am taking a cs class and have to check if a string is a palindrome with recursive functions. These functions are just to get the letters of a string User#21908 42 — 6y
0
Thanks User#21908 42 — 6y
View all comments (3 more)
0
What should I do instead? Also the class I am taking is having me use that function so User#21908 42 — 6y
0
that is what I started with. User#21908 42 — 6y
0
What might be a more efficient way to go about it? User#21908 42 — 6y
Ad

Answer this question