How to check if a letter is single and replace it?

  1. What do you want to achieve? I want to check if a character is single and replace it.

  2. What is the issue? I don’t really know how to do it.

  3. What solutions have you tried so far? I tried looking into string patterns but I couldn’t find one that helped me.

For example :

“He is Creative” == “He is Creative”

i am friendly!” == “I am friendly!”

i love my school!” == “I love my school!”

I really need help doing this since I want good grammar for my chat.

You’ll need a lot more than that if you want to improve the grammar and such in your chat. In the top example, “Creative” shouldn’t be capitalized.

If you ask me, I think you need to learn string manipulation on your own. It’s one of the most basic fundamentals of programming and it’s always one of the first topics covered in programming classes. You will get a lot more out of learning to do this properly than you will copying code from someone else here. This isn’t a complicated topic and you’ll need to learn it eventually.

I know I’m just giving examples of what I need. I posted a message here because I couldn’t figure it out.

They asked a question and you replied with “learn string manipulation”. They asked for help. On a from that was mostly made for helping. You just outright told them to learn something. It just sounds a bit rude. Especially the “on your own” part.

1 Like

To do this in the traditional way, you’ll iterate over the letters by number using string.sub and a for loop, and checking if the character at n-1 and n+1 are both spaces, then you will know that the letter at n is single and you can do stuff with it.

I’ve considered that choice but I want to learn to do it in the string pattern way. For now I’m marking this as a solution.

Then I recommend this website.

Thanks alot, I’ve been trying to learn string patterns for a while now!

1 Like
local function capitalSingles(str)
    local result -- initialize our final string
    words = str:split(" ") -- separate string into a table where each word is an element

    for i, word in ipairs(words) do -- loop thru each word
        if string.len(word) == 1 then -- if word is one letter
            words[i] = string.upper(words[i]) -- set the one letter word to upper case
        end
        result =  result.. ' '..words[i] -- add the word to our final string
    end

    return result -- return our final string
end

Not the best way of doing this, but it should work.

1 Like
local String = "i play a game with i"
String = string.gsub(String, "%s?i%s", "I ")
String = string.gsub(String, "%si%s?", " I")
print(String) --I play a game with I

Only the letter ‘i’ needs to be capitalised when isolated.

1 Like