trim
trim(string $string, string $characters = " \n\r\t\v\0"): string
Strips whitespace from both ends of a 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++; // trim leading whitespace
while (e > b && isspace((unsigned char)e[-1])) e--; // trim trailing whitespace
printf("[%.*s]\n", (int)(e - b), b);
return 0;
}
Output
[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;
}
Output
[hello]
C# v11.0.100
v11.0.100
Console.WriteLine("[" + " hello ".Trim() + "]");
Output
[hello]
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println("[" + strings.TrimSpace(" hello ") + "]")
}
Output
[hello]
Java v27.0.1
v27.0.1
public class Main {
public static void main(String[] args) {
System.out.println("[" + " hello ".trim() + "]");
}
}
Output
[hello]
JavaScript v26.13.1
v26.13.1
console.log("[" + " hello ".trim() + "]")
Output
[hello]
PHP v8.6.0
v8.6.0
echo "[" . trim(" hello ") . "]";
Output
[hello]
Python v3.15.2
v3.15.2
print("[" + " hello ".strip() + "]")
Output
[hello]
Rust v1.99.1
v1.99.1
fn main() {
println!("[{}]", " hello ".trim());
}
Output
[hello]
TypeScript v26.13.1
v26.13.1
console.log("[" + " hello ".trim() + "]");
Output
[hello]
Language differences
C: has no built-in containers or higher-order functions; the example trims whitespace by scanning with two pointers, whitespace only — the custom character-set argument is not implemented.
Go: strings.TrimSpace only trims Unicode whitespace.
Java: trims whitespace characters by default.
JavaScript: trims whitespace characters by default.
PHP: trims whitespace characters by default.
Python: strip can take a custom character set (e.g. .strip("xy")).
Rust: trim() strips leading/trailing Unicode whitespace.