字符串可以使用矩阵表示法进行连接(参见 字符串、字符数组),这通常是最自然的方法。例如:
fullname = [fname ".txt"]; email = ["<" user "@" domain ">"];
在每种情况下,都很容易看出最终的字符串是什么样子。这种方法也是最高效的。使用矩阵连接时,解析器会立即开始连接字符串,无需处理函数调用的开销以及相关函数的输入验证。
newline 函数可用于连接字符串,使得字符串在显示时呈现为多行文本。
c = newline ¶返回与换行符对应的字符。
这相当于 "\n"。
示例代码
joined_string = [newline "line1" newline "line2"] ⇒ line1 line2
此外,还有其他几个用于连接字符串对象的函数,在特定情况下可能很有用:char、strvcat、strcat 和 cstrcat。最后,还可以使用通用连接函数:参见 cat、horzcat 和 vertcat。
cstrcat 之外的所有字符串连接函数,都会将数字输入转换为字符数据——通过为每个元素(或多字节序列)取对应的 UTF-8 字符,如下例所示:char ([98, 97, 110, 97, 110, 97]) ⇒ banana
有关区域编码与 UTF-8 之间的转换,请参见 unicode2native 和 native2unicode。
char 和 strvcat 进行垂直连接,而 strcat 和 cstrcat 进行水平连接。例如:char ("an apple", "two pears")
⇒ an apple
two pears
strcat ("oc", "tave", " is", " good", " for you")
⇒ octave is good for you
char 在输出中为每个输入的空字符串生成一个空行。而 strvcat 则会消除空字符串。char ("orange", "green", "", "red")
⇒ orange
green
red
strvcat ("orange", "green", "", "red")
⇒ orange
green
red
cstrcat 之外的所有字符串连接函数也接受元胞数组数据(参见 元胞数组)。char 和 strvcat 将元胞数组转换为字符数组,而 strcat 则在元胞数组的各个单元内进行连接:char ({"red", "green", "", "blue"})
⇒ red
green
blue
strcat ({"abc"; "ghi"}, {"def"; "jkl"})
⇒
{
[1,1] = abcdef
[2,1] = ghijkl
}
strcat 会去除参数中的尾随空白(元胞数组内除外),而 cstrcat 则保留空白不变。这两种行为都可能很有用,如下面的示例所示:strcat (["dir1";"directory2"], ["/";"/"], ["file1";"file2"])
⇒ dir1/file1
directory2/file2
cstrcat (["thirteen apples"; "a banana"], [" 5$";" 1$"])
⇒ thirteen apples 5$
a banana 1$
请注意,上述 cstrcat 的示例中,空白来源于字符串数组中字符串的内部表示形式(参见 字符数组)。
C = char (A) ¶C = char (A, …) ¶C = char (str1, str2, …) ¶C = char (cell_array) ¶'' = char () ¶从单个或多个数值矩阵、字符矩阵或元胞数组创建字符串数组。
参数将被垂直连接。返回的值会根据需要填充空格,以使字符串数组的每一行具有相同的长度。输入中的空字符串是有意义的,并会出现在输出中。
对于数值输入,每个元素会被转换为相应的 ASCII 字符。如果输入超出 ASCII 范围(0-255),将产生范围错误。
对于元胞数组,每个元素会被分别连接。通过 char 转换的元胞数组大多可以使用 cellstr 转换回来。例如:
char ([97, 98, 99], "", {"98", "99", 100}, "str1", ["ha", "lf"])
⇒ ["abc "
" "
"98 "
"99 "
"d "
"str1"
"half"]
C = strvcat (A) ¶C = strvcat (A, …) ¶C = strvcat (str1, str2, …) ¶C = strvcat (cell_array) ¶从单个或多个数值矩阵、字符矩阵或元胞数组创建字符数组。
参数将被垂直连接。返回的值会根据需要填充空格,以使字符串数组的每一行具有相同的长度。与 char 不同,空字符串会被移除,不会出现在输出中。
对于数值输入,每个元素会被转换为相应的 ASCII 字符。如果输入超出 ASCII 范围(0-255),将产生范围错误。
对于元胞数组,每个元素会被分别连接。通过 strvcat 转换的元胞数组大多可以使用 cellstr 转换回来。例如:
strvcat ([97, 98, 99], "", {"98", "99", 100}, "str1", ["ha", "lf"])
⇒ ["abc "
"98 "
"99 "
"d "
"str1"
"half"]
str = strcat (s1, s2, …) ¶返回一个字符串,其中包含水平连接的所有参数。
如果参数是元胞字符串,strcat 返回一个各个元胞被连接后的元胞字符串。对于数值输入,每个元素被转换为相应的 ASCII 字符。在连接字符串之前,任何字符串输入的尾随空白都会被去除。请注意,元胞字符串的值不会被去除空白。
例如:
strcat ("|", " leading space is preserved", "|")
⇒ | leading space is preserved|
strcat ("|", "trailing space is eliminated ", "|")
⇒ |trailing space is eliminated|
strcat ("homogeneous space |", " ", "| is also eliminated")
⇒ homogeneous space || is also eliminated
s = [ "ab"; "cde" ];
strcat (s, s, s)
⇒
"ababab "
"cdecdecde"
s = { "ab"; "cd " };
strcat (s, s, s)
⇒
{
[1,1] = ababab
[2,1] = cd cd cd
}