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

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

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!

1 comment

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)

1 answer

✓ Accepted answer

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?

7 comments

0

string.sub(str) is just syntax sugar for str:sub()

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

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

0

Thanks

0

What should I do instead? Also the class I am taking is having me use that function so

0

that is what I started with.

0

What might be a more efficient way to go about it?

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