3

I have a string that includes all the characters which should be deleted in a given string. With a nested loop I can iterate through both strings. But is there a shorter way?

local ignore = "'`'"  

function ignoreLetters( c )
  local new = ""
  for cOrig in string.gmatch(c,".") do
    local addChar = 1
    for cIgnore in string.gmatch(ignore,".") do
      if cOrig == cIgnore then
        addChar = 0
        break  -- no other char possible
      end
    end
    if addChar>0 then new = new..cOrig end
  end
  return new
end

print(ignoreLetters("'s-Hertogenbosch"))
print(ignoreLetters("'s-Hertogen`bosch"))

The string ignore can also be a table if it makes the code shorter.

1 Answer 1

4

You can use string.gsub to replace any occurance of a given string in a string by another string. To delete the unwanted characters, simply replace them with an empty string.

local ignore = "'`'"  

function ignoreLetters( c )
  return (c:gsub("["..ignore.."]+", ""))
end

print(ignoreLetters("'s-Hertogenbosch"))
print(ignoreLetters("'s-Hertogen`bosch"))

Just be aware that in case you want to ignore magic characters you'll have to escape them in your pattern. But I guess this will give you a starting point and leave you plenty of own work to perfect.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.