Add str::replace
This commit is contained in:
parent
689f5f487c
commit
7e55061def
@ -52,6 +52,7 @@ export bytes_ivec;
|
||||
export unsafe_from_bytes_ivec;
|
||||
export is_empty;
|
||||
export is_not_empty;
|
||||
export replace;
|
||||
|
||||
native "rust" mod rustrt {
|
||||
type sbuf;
|
||||
@ -511,6 +512,22 @@ fn to_upper(str s) -> str {
|
||||
}
|
||||
ret outstr;
|
||||
}
|
||||
|
||||
// FIXME: This is super-inefficient
|
||||
fn replace(str s, str from, str to) : is_not_empty(from) -> str {
|
||||
// FIXME (694): Shouldn't have to check this
|
||||
check is_not_empty(from);
|
||||
if (byte_len(s) == 0u) {
|
||||
ret "";
|
||||
} else if (starts_with(s, from)) {
|
||||
ret to + replace(slice(s, byte_len(from), byte_len(s)),
|
||||
from, to);
|
||||
} else {
|
||||
ret unsafe_from_byte(s.(0))
|
||||
+ replace(slice(s, 1u, byte_len(s)), from, to);
|
||||
}
|
||||
}
|
||||
|
||||
// Local Variables:
|
||||
// mode: rust;
|
||||
// fill-column: 78;
|
||||
|
@ -132,6 +132,19 @@ fn test_is_not_empty() {
|
||||
assert !str::is_not_empty("");
|
||||
}
|
||||
|
||||
fn test_replace() {
|
||||
auto a = "a";
|
||||
check str::is_not_empty(a);
|
||||
assert str::replace("", a, "b") == "";
|
||||
assert str::replace("a", a, "b") == "b";
|
||||
assert str::replace("ab", a, "b") == "bb";
|
||||
auto test = "test";
|
||||
check str::is_not_empty(test);
|
||||
assert str::replace(" test test ", test, "toast")
|
||||
== " toast toast ";
|
||||
assert str::replace(" test test ", test, "") == " ";
|
||||
}
|
||||
|
||||
fn main() {
|
||||
test_bytes_len();
|
||||
test_index_and_rindex();
|
||||
@ -145,4 +158,15 @@ fn main() {
|
||||
test_ends_with();
|
||||
test_is_empty();
|
||||
test_is_not_empty();
|
||||
}
|
||||
test_replace();
|
||||
}
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// mode: rust;
|
||||
// fill-column: 78;
|
||||
// indent-tabs-mode: nil
|
||||
// c-basic-offset: 4
|
||||
// buffer-file-coding-system: utf-8-unix
|
||||
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
|
||||
// End:
|
||||
|
Loading…
Reference in New Issue
Block a user