在Lua中拆分字符串

时间:2017-12-18 16:07:31

标签: lua

我对Lua很新,很抱歉,如果我听起来很蠢。 我正在尝试制作一个类似这样的程序:

用户输入:“Hello world” Var1:你好 Var2:世界

因为我不知道我在做什么,所以我只有test = io.read(),我不知道下一步该做什么。

我感谢任何帮助!

谢谢,摩根。

1 个答案:

答案 0 :(得分:2)

如果你想要分词,你可以这样做:

map_df(group_vars, ~group_by_at(mtcars, .x) %>% 
                summarise(  mean_mgp = mean(mpg),
                        median_mpg = median(mpg),
                        count = n()) %>%
                setNames(c("am", "variable_column", "mean_mpg", "median_mpg", "count")),
            .id="variable_col_name") %>%
            mutate(variable_col_name = variable_grp[as.numeric(variable_col_name)])

# A tibble: 17 x 6
# Groups:   am [2]
   # variable_col_name    am variable_column mean_mpg median_mpg count
               # <chr> <dbl>           <dbl>    <dbl>      <dbl> <int>
 # 1                vs     0               0 15.05000      15.20    12
 # 2                vs     0               1 20.74286      21.40     7
 # 3                vs     1               0 19.75000      20.35     6
 # 4                vs     1               1 28.37143      30.40     7
 # 5              gear     0               3 16.10667      15.50    15
 # 6              gear     0               4 21.05000      21.00     4
 # 7              gear     1               4 26.27500      25.05     8
 # 8              gear     1               5 21.38000      19.70     5
 # 9              carb     0               1 20.33333      21.40     3
# 10              carb     0               2 19.30000      18.95     6
# 11              carb     0               3 16.30000      16.40     3
# 12              carb     0               4 14.30000      14.30     7
# 13              carb     1               1 29.10000      29.85     4
# 14              carb     1               2 27.05000      28.20     4
# 15              carb     1               4 19.26667      21.00     3
# 16              carb     1               6 19.70000      19.70     1
# 17              carb     1               8 15.00000      15.00     1

输出:

input = "Hello world"

-- declare a table to store the results
-- use tables instead of single variables, if you don't know how many results you'll have
t_result = {}

-- scan the input
for k in input:gmatch('(%w+)') do table.insert(t_result, k) end
-- input:gmatch('(%w+)')
-- with generic match function will the input scanned for matches by the given pattern
-- it's the same like: string.gmatch(input, '(%w+)')
-- meaning of the search pattern:
---- "%w" = word character
---- "+"  = one or more times
---- "()" = capture the match and return it to the searching variable "k"

-- table.insert(t_result, k)
-- each captured occurence of search result will stored in the result table

-- output
for i=1, #t_result do print(t_result[i]) end
-- #t_result: with "#" you get the length of the table (it's not usable for each kind of tables)
-- other way:
-- for k in pairs(t_result) do print(t_result[k]) end