trim

trim(string $string, string $characters = " \n\r\t\v\0"): string

去除字符串首尾的空白字符。

C C23

C23
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void) {
    const char *s = "  hello  ";
    const char *b = s;
    const char *e = s + strlen(s);
    while (b < e && isspace((unsigned char)*b)) b++;   // 去除前导空白
    while (e > b && isspace((unsigned char)e[-1])) e--; // 去除尾随空白
    printf("[%.*s]\n", (int)(e - b), b);
    return 0;
}
输出
[hello]

C++ C++26

C++26
#include <cctype>
#include <iostream>
#include <string>
int main() {
    std::string s = "  hello  ";
    size_t b = 0, e = s.size();
    while (b < e && std::isspace((unsigned char)s[b])) b++;
    while (e > b && std::isspace((unsigned char)s[e - 1])) e--;
    std::string t = s.substr(b, e - b);
    std::cout << "[" << t << "]\n";
    return 0;
}
输出
[hello]

C# v11.0.100

v11.0.100
Console.WriteLine("[" + "  hello  ".Trim() + "]");
输出
[hello]

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println("[" + strings.TrimSpace("  hello  ") + "]")
}
输出
[hello]

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        System.out.println("[" + "  hello  ".trim() + "]");
    }
}
输出
[hello]

JavaScript v26.13.1

v26.13.1
console.log("[" + "  hello  ".trim() + "]")
输出
[hello]

PHP v8.6.0

v8.6.0
echo "[" . trim("  hello  ") . "]";
输出
[hello]

Python v3.15.2

v3.15.2
print("[" + "  hello  ".strip() + "]")
输出
[hello]

Rust v1.99.1

v1.99.1
fn main() {
    println!("[{}]", "  hello  ".trim());
}
输出
[hello]

TypeScript v26.13.1

v26.13.1
console.log("[" + "  hello  ".trim() + "]");
输出
[hello]

语言差异说明

C:无内置容器与高阶函数,示例以双指针扫描去除空白实现;示例仅处理空白字符,自定义字符集参数未实现。

Go:strings.TrimSpace 只去 Unicode 空白。

Java:默认去空白字符。

JavaScript:默认去空白字符。

PHP:默认去空白字符。

Python:strip 可指定要去除的字符集(如 .strip("xy"))。

Rust:trim() 去除首尾 Unicode 空白字符。