我有一个大字符串(base64编码的图像),长度为1050个字符。如何在C
中附加一个由小的字符串组成的大字符串 function GetIcon()
return "Bigggg string 1"\
"continuation of string"\
"continuation of string"\
"End of string"
答案 0 :(得分:31)
根据Programming in Lua 2.4 Strings:
我们也可以通过匹配双方括号[[...]]来分隔文字字符串。这种括号中的文字可能会运行几行,可能会嵌套,并且不会解释转义序列。此外,当此字符是换行符时,此表单忽略字符串的第一个字符。这种形式对于编写包含程序片段的字符串特别方便;例如,
page = [[
<HTML>
<HEAD>
<TITLE>An HTML Page</TITLE>
</HEAD>
<BODY>
<A HREF="http://www.lua.org">Lua</A>
[[a text between double brackets]]
</BODY>
</HTML>
]]
这是你要求的最接近的东西,但是使用上面的方法会将换行符保留在字符串中,所以这不会直接起作用。
您也可以使用字符串连接(使用..):
value = "long text that" ..
" I want to carry over" ..
"onto multiple lines"
答案 1 :(得分:15)
这里的大多数答案在运行时而不是在编译时解决了这个问题。
Lua 5.2引入了转义序列\z
来优雅地解决这个问题,而不会产生任何运行时费用。
> print "This is a long \z
>> string with \z
>> breaks in between, \z
>> and is spanning multiple lines \z
>> but still is a single string only!"
This is a long string with breaks in between, and is spanning multiple lines but still is a single string only!
\z
跳过字符串文字 1 中的所有后续字符,直到第一个非空格字符。这也适用于非多行文字文本。
> print "This is a simple \z string"
This is a simple string
转义序列'\ z'跳过以下白色空格字符范围,包括换行符;将长文字字符串分解并缩进多行而不将新行和空格添加到字符串内容中特别有用。
1:所有转义序列(包括\z
)仅适用于短文字字符串("…"
,'…'
),并且可以理解, on long literal strings ([[...]]
等)
答案 2 :(得分:3)
我将所有块放在一个表中并在其上使用table.concat
。这避免了在每个连接处创建新字符串。例如(不计算Lua中字符串的开销):
-- bytes used
foo="1234".. -- 4 = 4
"4567".. -- 4 + 4 + 8 = 16
"89ab" -- 16 + 4 + 12 = 32
-- | | | \_ grand total after concatenation on last line
-- | | \_ second operand of concatenation
-- | \_ first operand of concatenation
-- \_ total size used until last concatenation
正如您所看到的,这种爆炸非常迅速。最好是:
foo=table.concat{
"1234",
"4567",
"89ab"}
大约需要3 * 4 + 12 = 24个字节。
答案 3 :(得分:1)
你试过吗? string.sub(s,i [,j])函数。 你可能想看看这里:
答案 4 :(得分:0)
此:
return "Bigggg string 1"\
"continuation of string"\
"continuation of string"\
"End of string"
C / C ++语法使编译器将其全部视为一个大字符串。它通常用于可读性。
Lua的等价物是:
return "Bigggg string 1" ..
"continuation of string" ..
"continuation of string" ..
"End of string"
请注意,C / C ++语法是编译时,而Lua等效语言可能在运行时进行连接(尽管编译器理论上可以对其进行优化)。这应该不是什么大问题。