11

split()in的对立面是awk什么?想象一下,我有数组包含字符/整数。

我试过的:

color = "#FFFF00";
printf("color original: %s\n", color);
split(color, chars, "");
joined = "";
for (i=1; i <= length(chars); i++) {
    joined = joined + chars[i];
}
printf("color joined: %s\n", joined);

但是输出是:

color original: #FFFF00
color joined: 0

这当然是不正确的。

更新: 很酷,最终得到以下代码(灵感来自答案中的连接函数):

color = "#FFFF00";
printf("color original: %s\n", color);
split(color, chars, "");
joined = "";
for (i=1; i <= length(chars); i++) {
    joined = joined "" chars[i];
}
printf("color joined: %s\n", joined);

诀窍是在加入事物时不要使用+符号

4

5 回答 5

16

这是一个不依赖 gawk 或不知道数组长度的解决方案,如果您愿意,可以在每个数组元素之间放置一个分隔符(在这种情况下为空格)字符串:

color = "#FFFF00"
printf "color original: %s\n", color
split(color, chars, "")
joined = sep = ""
for (i=1; i in chars; i++) {
    joined = joined sep chars[i]
    sep = " "     # populate sep here with whatever string you want between elements
}
printf "color joined: %s\n", joined

我还清理了 printf 的错误使用和虚假的分号。

于 2012-11-30T15:57:00.930 回答
1

这是 POSIX awk 的一种方法:

br = "red,orange,yellow,green,blue"
ch = split(br, de, ",")
print "original: " br
printf "joined: "
for (ec in de) printf ec == ch ? de[ec] "\n" : de[ec] "-"

输出:

original: red,orange,yellow,green,blue
joined: red-orange-yellow-green-blue
于 2016-06-12T15:09:45.700 回答
0

你想要的(在你的循环中)是string concatenation

于 2012-11-30T09:01:42.470 回答
0

与以前的答案类似,但不那么优雅,但简单而简短:

color = "#FFFF00"
printf "color original: %s\n", color
split(color, chars, "")
for (i=1; i<=length(chars); i++) {
    (i==1) ? joined = chars[i] : joined = joined" "chars[i] # Define separator here
}
printf "color joined: %s\n", joined
于 2022-01-17T19:40:03.430 回答
-2

知道与之相反的split()join(),仅仅谷歌搜索就会给我这个页面,它似乎包含解决方案:http ://www.gnu.org/software/gawk/manual/html_node/Join-Function.html 。它将数组的所有元素连接在一起,并返回相应的字符串。

['f','o','o'] => "foo"

玩得开心

于 2012-11-30T09:01:49.270 回答