Is there any way to get a particular line from a string?

Asked

Viewed 142 times

3

I have this example string:

s = [[Pão
com
Requeijão]]

Is there any way to get only the second line of the string? If so, how?

  • 1

    Bread with cottage cheese is so great.

  • 1

    Psé ne

3 answers

3

The second line of the string s is the result of s:match("\n(.-)\n").

  • Dps of this is required a p/skip the n: :sub(1).

  • @Hydro, why? The result of s:match("\n(.-)\n") does not contain any \n.

1

Yes, there is.

In moon the terminus of a line is signalled by \n, that is, the solution is to break the line from the \n and take the second element. See how it would look:

if s:sub(-1) ~= "\n" then s = s.."\n" end --Garante que tenha um '\n' no final da linha
linhas = {} --Cria um array/table

for linha in string.gmatch(s, "(.-)\n") do --Itera sobre as linhas
    table.insert(linhas, linha) --Adiciona ao array linhas
end

See working on Ideone.

1

I would split the string based on the rows and then take the second row indexing the resulting table. Ex:

s=[[Pão
com
Requeijão]]

function split(str, sep)
    local ret = {}
    str = table.concat{str, sep}
    for part in string.gmatch(str, "(.-)" .. sep) do
        table.insert(ret, part)
    end
    return ret
end

lines = split(s, "\n")

print(lines[2])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.