Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Word by Word string partition in Lua
-- This program demonstrates the use of loops, if statements, -- how to traverse through a loop using -- the 'for' loop, declaring a function and using it as well. local find_index = function(str, character) -- Custom function to find the index of a character for i = 1, #str do -- Going through the string using loop ('i' denotes the index.) if string.char(str:byte(i)) == character then -- Checking if we found the first occurance of the required character. return i -- Stopping the loop and returning the index. end -- Ending the 'if' statement. end -- Ending the 'for' loop. return nil -- If the required character wasn't found then the -- function won't stop running and will return 'nil'. end local str = io.read("*l") .. " " -- Taking the input. local space_counter = 0 -- Number of spaces. for i = 0, #str do -- Looping through the string. local space_index = find_index(str, " ") -- Index of the space character. if space_index == nil then -- If the string has come to an end then stop the loop. break else local substring = string.sub(str, 0, space_index) -- Slicing out the first word print(substring) -- Printing the word. str = string.sub(str, space_index + 1, #str) -- Removing the first word of the string and reassigning it. space_counter = space_counter + 1 -- Incrementing the number of space end end print("Number of space_indexes in String: " .. space_counter - 1) -- Printing (space - 1) as we increased the number of spaces at the beginning. -- PROGRAM BY 'JAMES COLLINS'
run
|
edit
|
history
|
help
2
test
Volume of sphere
test random skill id
test123
1
as
W.I.P
PAID HACK PuBG
Lua properties
Convert MySQL 'framed' table into CSV