2
whiteSpace = 0
foo = "foo bar"

for i = 1, #foo do
    if (string.sub(foo, i, i) == "%") then
        whiteSpace = whiteSpace + 1
    end
end

print(whiteSpace)

I'm trying to loop through this string in each character, check if it is whitespace. If the character is whitespace, I want to increment the whiteSpace variable and output it at the end. But for some reason when I execute it, it always returns 0, even though there is clearly whitespace within the foo string.

I've used "%", "%s" and "" with no avail. Pretty clueless right now.

2 Answers 2

3
whiteSpace = 0
foo = "foo bar"

for i = 1, #foo do
    if (string.sub(foo, i, i) == " ") then
        whiteSpace = whiteSpace + 1
    end
end

print(whiteSpace)

with pattern matching

a, whiteSpace = string.gsub("foo bar","%s","")
print(whiteSpace)
Sign up to request clarification or add additional context in comments.

Comments

1
whiteSpace = 0
foo = "foo bar"
foo = string.gsub(foo, "%s", " ")

for i = 1, #foo do
    if (string.sub(foo, i, i) == " ") then
        whiteSpace = whiteSpace + 1
    end
end

print(whiteSpace)

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.