ltrim / rtrim

ltrim(string $string, string $characters = " \t\n\r\0\x0B"): string · rtrim(string $string, string $characters = " \t\n\r\0\x0B"): string

定向裁剪:ltrim 只裁左侧、rtrim 只裁右侧(默认空白集与 trim 相同),charlist 是字符集合而非前缀/后缀字符串——ltrim('Hello, World!', 'He') 裁掉字符 H 和 e,不是字符串 'He'。

C C23

C23
#include <stdio.h>
#include <string.h>

/* 无裁剪 API:手写 cutset 循环(与 PHP charlist 同一套集合语义) */
static const char *ltrim_set(const char *s, const char *set) {
    while (*s && strchr(set, (unsigned char)*s)) { s++; }
    return s;
}

static void rtrim_set(char *s, const char *set) {
    size_t n = strlen(s);
    while (n > 0 && strchr(set, (unsigned char)s[n - 1])) { s[--n] = '\0'; }
}

int main(void) {
    printf("[%s]\n", ltrim_set("  hello  ", " "));
    char a[] = "  hello  ";
    rtrim_set(a, " ");
    printf("[%s]\n", a);
    printf("[%s]\n", ltrim_set("Hello, World!", "He"));
    printf("[%s]\n", ltrim_set("abcbcXYZ", "abc"));
    char b[] = "test.php";
    rtrim_set(b, ".php");
    printf("[%s]\n", b);
    return 0;
}
输出
[hello  ]
[  hello]
[llo, World!]
[XYZ]
[test]

C++ C++26

C++26
#include <iostream>
#include <string>

// find_first_not_of / find_last_not_of:内建集合语义(同 PHP charlist)
static std::string ltrim_set(const std::string &s, const std::string &set) {
    auto pos = s.find_first_not_of(set);
    return s.substr(pos == std::string::npos ? s.size() : pos);
}

static std::string rtrim_set(const std::string &s, const std::string &set) {
    auto pos = s.find_last_not_of(set);
    return s.substr(0, pos == std::string::npos ? 0 : pos + 1);
}

int main() {
    std::cout << "[" << ltrim_set("  hello  ", " ") << "]\n";
    std::cout << "[" << rtrim_set("  hello  ", " ") << "]\n";
    std::cout << "[" << ltrim_set("Hello, World!", "He") << "]\n";
    std::cout << "[" << ltrim_set("abcbcXYZ", "abc") << "]\n";
    std::cout << "[" << rtrim_set("test.php", ".php") << "]\n";
    return 0;
}
输出
[hello  ]
[  hello]
[llo, World!]
[XYZ]
[test]

C# v11.0.100

v11.0.100
using System;

// TrimStart/TrimEnd(params char[]):内建集合语义(同 PHP charlist)
Console.WriteLine($"[{"  hello  ".TrimStart()}]");
Console.WriteLine($"[{"  hello  ".TrimEnd()}]");
Console.WriteLine($"[{"Hello, World!".TrimStart('H', 'e')}]");
Console.WriteLine($"[{"abcbcXYZ".TrimStart('a', 'b', 'c')}]");
Console.WriteLine($"[{"test.php".TrimEnd('.', 'p', 'h')}]");
输出
[hello  ]
[  hello]
[llo, World!]
[XYZ]
[test]

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strings"
)

// strings.TrimLeft/TrimRight:cutset 是字符集合(与 PHP charlist 语义相同)
func main() {
	fmt.Printf("[%s]\n", strings.TrimLeft("  hello  ", " "))
	fmt.Printf("[%s]\n", strings.TrimRight("  hello  ", " "))
	fmt.Printf("[%s]\n", strings.TrimLeft("Hello, World!", "He"))
	fmt.Printf("[%s]\n", strings.TrimLeft("abcbcXYZ", "abc"))
	fmt.Printf("[%s]\n", strings.TrimRight("test.php", ".php"))
}
输出
[hello  ]
[  hello]
[llo, World!]
[XYZ]
[test]

Java v27.0.1

v27.0.1
public class Main {
    // 无 cutset API:strip* 只认 Unicode 空白;字符集合语义需手写循环
    // (实战用 Apache commons-lang3 的 StringUtils.stripStart/stripEnd)
    static String ltrimSet(String s, String set) {
        int i = 0;
        while (i < s.length() && set.indexOf(s.charAt(i)) >= 0) i++;
        return s.substring(i);
    }

    static String rtrimSet(String s, String set) {
        int i = s.length();
        while (i > 0 && set.indexOf(s.charAt(i - 1)) >= 0) i--;
        return s.substring(0, i);
    }

    public static void main(String[] args) {
        System.out.println("[" + "  hello  ".stripLeading() + "]");
        System.out.println("[" + "  hello  ".stripTrailing() + "]");
        System.out.println("[" + ltrimSet("Hello, World!", "He") + "]");
        System.out.println("[" + ltrimSet("abcbcXYZ", "abc") + "]");
        System.out.println("[" + rtrimSet("test.php", ".php") + "]");
    }
}
输出
[hello  ]
[  hello]
[llo, World!]
[XYZ]
[test]

JavaScript v26.13.1

v26.13.1
// trimStart/trimEnd 只裁空白——无 charlist:手写集合语义
const ltrim = (s, set = " \t\n\r\v\f\0") => {
    let i = 0;
    while (i < s.length && set.includes(s[i])) i++;
    return s.slice(i);
};
const rtrim = (s, set = " \t\n\r\v\f\0") => {
    let i = s.length;
    while (i > 0 && set.includes(s[i - 1])) i--;
    return s.slice(0, i);
};
console.log(`[${ltrim("  hello  ")}]`);
console.log(`[${rtrim("  hello  ")}]`);
console.log(`[${ltrim("Hello, World!", "He")}]`);
console.log(`[${ltrim("abcbcXYZ", "abc")}]`);
console.log(`[${rtrim("test.php", ".php")}]`);
输出
[hello  ]
[  hello]
[llo, World!]
[XYZ]
[test]

PHP v8.6.0

v8.6.0
// 默认裁空白,方向明确:只左 / 只右
$s = "  hello  ";
echo "[" . ltrim($s) . "]\n";
echo "[" . rtrim($s) . "]\n";
// charlist 是字符集合,不是前缀/后缀字符串
echo "[" . ltrim("Hello, World!", "He") . "]\n"; // 从开头裁掉 H 和 e
echo "[" . ltrim("abcbcXYZ", "abc") . "]\n";     // 开头整段都在集合内
echo "[" . rtrim("test.php", ".php") . "]\n";    // 结尾字符都在集合内
输出
[hello  ]
[  hello]
[llo, World!]
[XYZ]
[test]

Python v3.15.2

v3.15.2
# lstrip/rstrip:直接对应物(参数是字符集合,语义相同)
s = "  hello  "
print(f"[{s.lstrip()}]")
print(f"[{s.rstrip()}]")
print(f"[{'Hello, World!'.lstrip('He')}]")  # 字符集合,不是前缀串
print(f"[{'abcbcXYZ'.lstrip('abc')}]")      # 开头整段都在集合内
print(f"[{'test.php'.rstrip('.php')}]")
输出
[hello  ]
[  hello]
[llo, World!]
[XYZ]
[test]

Rust v1.99.1

v1.99.1
fn main() {
    // trim_start_matches/trim_end_matches 接受字符切片 pattern:内建集合语义
    println!("[{}]", "  hello  ".trim_start_matches(&[' ', '\t', '\n', '\r'][..]));
    println!("[{}]", "  hello  ".trim_end_matches(&[' ', '\t', '\n', '\r'][..]));
    println!("[{}]", "Hello, World!".trim_start_matches(&['H', 'e'][..]));
    println!("[{}]", "abcbcXYZ".trim_start_matches(&['a', 'b', 'c'][..]));
    println!("[{}]", "test.php".trim_end_matches(&['.', 'p', 'h'][..]));
}
输出
[hello  ]
[  hello]
[llo, World!]
[XYZ]
[test]

TypeScript v26.13.1

v26.13.1
// trimStart/trimEnd 只裁空白——无 charlist:手写集合语义
const ltrim = (s: string, set: string = " \t\n\r\v\f\0"): string => {
    let i = 0;
    while (i < s.length && set.includes(s[i])) i++;
    return s.slice(i);
};
const rtrim = (s: string, set: string = " \t\n\r\v\f\0"): string => {
    let i = s.length;
    while (i > 0 && set.includes(s[i - 1])) i--;
    return s.slice(0, i);
};
console.log(`[${ltrim("  hello  ")}]`);
console.log(`[${rtrim("  hello  ")}]`);
console.log(`[${ltrim("Hello, World!", "He")}]`);
console.log(`[${ltrim("abcbcXYZ", "abc")}]`);
console.log(`[${rtrim("test.php", ".php")}]`);
输出
[hello  ]
[  hello]
[llo, World!]
[XYZ]
[test]

语言差异说明

与既有 trim 条目对照:trim 两侧齐裁,ltrim/rtrim 定向单侧——三者共享同一 charlist 参数语义与默认空白集 " \t\n\r\0\x0B"。集合语义是最大教学点:ltrim("Hello, World!", "He") 裁掉的是「字符集合 {H,e}」,得到 "llo, World!"——不是裁掉前缀字符串 "He";ltrim("abcbcXYZ","abc") 会把 a/b/c 开头整段吃干净("XYZ"),也证明按集合逐字符判定。

十语言版图(集合语义内建程度递减):Python lstrip/rstrip 与 PHP 完全同构(chars 参数集);C# TrimStart/TrimEnd(params char[]);Go strings.TrimLeft/TrimRight(cutset);Rust trim_start_matches(char slice pattern);C++ find_first_not_of/find_last_not_of——以上皆内建集合语义。Java stripLeading/stripTrailing 只认 Unicode 空白(比 PHP 默认集宽,含 U+2028 等),无 cutset 形态(commons-lang3 stripStart/stripEnd 补);JS trimStart/trimEnd 同样只裁空白且无参数(手写 includes 循环,示例默认集含 \0 补齐 PHP 集);C 无任何裁剪函数(手写 strchr 循环,注意 (unsigned char) 转换防负索引 UB)。

Unicode 细节:Java 的 strip 家族按 Character.isWhitespace 判定(连 U+00A0 不算空白但 U+2028 算);Python/PHP 默认集是 ASCII 空白——同一段「带不间断空格」的文本三语言裁剪结果可能不同。空集边界:charlist 为空串时 PHP 不裁任何字符;C++ find_first_not_of 空集返 npos(示例以 npos 分支兜底)。