Add .insert() and .insert_char() methods to ~str.
This commit is contained in:
@@ -2510,6 +2510,16 @@ pub trait OwnedStr {
|
|||||||
/// Prepend a char to a string
|
/// Prepend a char to a string
|
||||||
fn unshift_char(&mut self, ch: char);
|
fn unshift_char(&mut self, ch: char);
|
||||||
|
|
||||||
|
/// Insert a new sub-string at the given position in a string, in O(n + m) time
|
||||||
|
/// (with n and m the lengths of the string and the substring.)
|
||||||
|
/// This fails if `position` is not at a character boundary.
|
||||||
|
fn insert(&mut self, position: uint, substring: &str);
|
||||||
|
|
||||||
|
/// Insert a char at the given position in a string, in O(n + m) time
|
||||||
|
/// (with n and m the lengths of the string and the substring.)
|
||||||
|
/// This fails if `position` is not at a character boundary.
|
||||||
|
fn insert_char(&mut self, position: uint, ch: char);
|
||||||
|
|
||||||
/// Concatenate two strings together.
|
/// Concatenate two strings together.
|
||||||
fn append(self, rhs: &str) -> ~str;
|
fn append(self, rhs: &str) -> ~str;
|
||||||
|
|
||||||
@@ -2622,6 +2632,24 @@ impl OwnedStr for ~str {
|
|||||||
*self = new_str;
|
*self = new_str;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn insert(&mut self, position: uint, substring: &str) {
|
||||||
|
// This could be more efficient.
|
||||||
|
let mut new_str = self.slice_to(position).to_owned();
|
||||||
|
new_str.push_str(substring);
|
||||||
|
new_str.push_str(self.slice_from(position));
|
||||||
|
*self = new_str;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn insert_char(&mut self, position: uint, ch: char) {
|
||||||
|
// This could be more efficient.
|
||||||
|
let mut new_str = self.slice_to(position).to_owned();
|
||||||
|
new_str.push_char(ch);
|
||||||
|
new_str.push_str(self.slice_from(position));
|
||||||
|
*self = new_str;
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn append(self, rhs: &str) -> ~str {
|
fn append(self, rhs: &str) -> ~str {
|
||||||
let mut new_str = self;
|
let mut new_str = self;
|
||||||
@@ -2874,6 +2902,20 @@ mod tests {
|
|||||||
assert_eq!(~"华ประเทศไทย中", data);
|
assert_eq!(~"华ประเทศไทย中", data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_insert_char() {
|
||||||
|
let mut data = ~"ประเทศไทย中";
|
||||||
|
data.insert_char(15, '华');
|
||||||
|
assert_eq!(~"ประเท华ศไทย中", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_insert() {
|
||||||
|
let mut data = ~"ประเทศไทย中";
|
||||||
|
data.insert(15, "华中");
|
||||||
|
assert_eq!(~"ประเท华中ศไทย中", data);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_collect() {
|
fn test_collect() {
|
||||||
let empty = ~"";
|
let empty = ~"";
|
||||||
|
|||||||
Reference in New Issue
Block a user