implode
implode(string $separator, array $array): string
用分隔符把数组元素连接成一个字符串。
C C23
C23
#include <stdio.h>
int main(void) {
const char *xs[] = {"a", "b", "c"};
for (int i = 0; i < 3; i++) {
printf(i ? "-%s" : "%s", xs[i]);
}
printf("\n");
return 0;
}
输出
a-b-c
C++ C++26
C++26
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> xs = {"a", "b", "c"};
for (size_t i = 0; i < xs.size(); ++i) {
if (i) std::cout << "-";
std::cout << xs[i];
}
std::cout << "\n";
return 0;
}
输出
a-b-c
C# v11.0.100
v11.0.100
var xs = new List<string> { "a", "b", "c" };
Console.WriteLine(string.Join("-", xs));
输出
a-b-c
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Join([]string{"a", "b", "c"}, "-"))
}
输出
a-b-c
Java v27.0.1
v27.0.1
public class Main {
public static void main(String[] args) {
System.out.println(String.join("-", "a", "b", "c"));
}
}
输出
a-b-c
JavaScript v26.13.1
v26.13.1
console.log(["a", "b", "c"].join("-"))
输出
a-b-c
PHP v8.6.0
v8.6.0
echo implode("-", ["a", "b", "c"]);
输出
a-b-c
Python v3.15.2
v3.15.2
print("-".join(["a", "b", "c"]))
输出
a-b-c
Rust v1.99.1
v1.99.1
fn main() {
let xs = vec!["a", "b", "c"];
println!("{}", xs.join("-"));
}
输出
a-b-c
TypeScript v26.13.1
v26.13.1
const xs: string[] = ["a", "b", "c"];
console.log(xs.join("-"));
输出
a-b-c
语言差异说明
C:无内置容器与高阶函数,示例以固定数组/缓冲与手写循环实现。
Go:strings.Join(arr, sep)。
Java:String.join(sep, ...)。
JavaScript:把数组挂前面 arr.join(sep)。
PHP:implode(sep, arr)。
Python:把分隔符挂前面 sep.join(list)。
Rust:对字符串数组用 join 方法拼接。