Add std::str::trim/trim_left/trim_right
This commit is contained in:
parent
598e25e091
commit
1ad68eafd2
@ -54,6 +54,9 @@ export is_empty;
|
||||
export is_not_empty;
|
||||
export replace;
|
||||
export char_slice;
|
||||
export trim_left;
|
||||
export trim_right;
|
||||
export trim;
|
||||
|
||||
native "rust" mod rustrt {
|
||||
type sbuf;
|
||||
@ -524,6 +527,42 @@ fn char_slice(s: &str, begin: uint, end: uint) -> str {
|
||||
from_chars(vec::slice(to_chars(s), begin, end))
|
||||
}
|
||||
|
||||
fn trim_left(s: &str) -> str {
|
||||
fn count_whities(s: &vec[char]) -> uint {
|
||||
let i = 0u;
|
||||
while i < vec::len(s) {
|
||||
if !char::is_whitespace(s.(i)) {
|
||||
break;
|
||||
}
|
||||
i += 1u;
|
||||
}
|
||||
ret i;
|
||||
}
|
||||
let chars = to_chars(s);
|
||||
let whities = count_whities(chars);
|
||||
ret from_chars(vec::slice(chars, whities, vec::len(chars)));
|
||||
}
|
||||
|
||||
fn trim_right(s: &str) -> str {
|
||||
fn count_whities(s: &vec[char]) -> uint {
|
||||
let i = vec::len(s);
|
||||
while 0u < i {
|
||||
if !char::is_whitespace(s.(i - 1u)) {
|
||||
break;
|
||||
}
|
||||
i -= 1u;
|
||||
}
|
||||
ret i;
|
||||
}
|
||||
let chars = to_chars(s);
|
||||
let whities = count_whities(chars);
|
||||
ret from_chars(vec::slice(chars, 0u, whities));
|
||||
}
|
||||
|
||||
fn trim(s: &str) -> str {
|
||||
trim_left(trim_right(s))
|
||||
}
|
||||
|
||||
// Local Variables:
|
||||
// mode: rust;
|
||||
// fill-column: 78;
|
||||
|
@ -162,6 +162,36 @@ fn test_char_slice() {
|
||||
assert (str::eq("\u65e5", str::char_slice("\u65e5\u672c", 0u, 1u)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_left() {
|
||||
assert str::trim_left("") == "";
|
||||
assert str::trim_left("a") == "a";
|
||||
assert str::trim_left(" ") == "";
|
||||
assert str::trim_left(" blah") == "blah";
|
||||
assert str::trim_left(" \u3000 wut") == "wut";
|
||||
assert str::trim_left("hey ") == "hey ";
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_right() {
|
||||
assert str::trim_right("") == "";
|
||||
assert str::trim_right("a") == "a";
|
||||
assert str::trim_right(" ") == "";
|
||||
assert str::trim_right("blah ") == "blah";
|
||||
assert str::trim_right("wut \u3000 ") == "wut";
|
||||
assert str::trim_right(" hey") == " hey";
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim() {
|
||||
assert str::trim("") == "";
|
||||
assert str::trim("a") == "a";
|
||||
assert str::trim(" ") == "";
|
||||
assert str::trim(" blah ") == "blah";
|
||||
assert str::trim("\nwut \u3000 ") == "wut";
|
||||
assert str::trim(" hey dude ") == "hey dude";
|
||||
}
|
||||
|
||||
// Local Variables:
|
||||
// mode: rust;
|
||||
// fill-column: 78;
|
||||
|
Loading…
x
Reference in New Issue
Block a user