Contents
输出结果
aaa
程式码
C
#include <stdio.h> #include <string.h> #include <stdlib.h> char *ltrim(char *str, const char *seps) { size_t totrim; if (seps == NULL) { seps = "\t\n\v\f\r "; } totrim = strspn(str, seps); if (totrim > 0) { size_t len = strlen(str); if (totrim == len) { str[0] = '\0'; } else { memmove(str, str + totrim, len + 1 - totrim); } } return str; } char *rtrim(char *str, const char *seps) { int i; if (seps == NULL) { seps = "\t\n\v\f\r "; } i = strlen(str) - 1; while (i >= 0 && strchr(seps, str[i]) != NULL) { str[i] = '\0'; i--; } return str; } char *trim(char *str, const char *seps) { return ltrim(rtrim(str, seps), seps); } int main(void) { char str[] = " aaa \n\t"; trim(str, NULL); printf("%s\n", str); return 0; }
C++
#include <iostream> using namespace std; int main() { const std::string& chars = "\t\n\v\f\r "; std::string str = " aaa \n\t"; str.erase(str.find_last_not_of(chars) + 1); str.erase(0, str.find_first_not_of(chars)); std::cout << str << endl; }
C#
using System; public class Trim { public void printTrim() { String str = " aaa \n\t"; Console.WriteLine(str.Trim()); } public static void Main() { Trim tm = new Trim(); tm.printTrim(); } }
Go
package main import "fmt" import "strings" func main() { str := " aaa \n\t" fmt.Println(strings.TrimSpace(str)) }
Java
public class Trim { public static void main(String[] args) { String str = " aaa \n\t"; System.out.println(str.trim()); } }
JavaScript
let str = " aaa \n\t"; console.log(str.trim());
Perl
my $a = " aaa \n\t"; $a=~ s!^\s*|\s*$!!gs; print($a."\n");
PHP
<?php $a = " aaa \n\t"; print(trim($a)."\n");
Python
str = " aaa \n\t" print(str.strip())
Ruby
str = " aaa \n\t" print(str.strip()+"\n")
Rust
fn main() { let str = " aaa \n\t"; println!("{}", str.trim()); }
Shell
echo " aaa \n\t" | xargs;