Skip to content

Commit 4b0f29a

Browse files
committed
core: add char_at_reverse
1 parent fe74a1c commit 4b0f29a

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

src/libcore/str.rs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1769,7 +1769,7 @@ pub pure fn char_range_at(s: &str, i: uint) -> CharRange {
17691769
return CharRange {ch: val as char, next: i};
17701770
}
17711771

1772-
/// Pluck a character out of a string
1772+
/// Plucks the `n`th character from the beginning of a string
17731773
pub pure fn char_at(s: &str, i: uint) -> char {
17741774
return char_range_at(s, i).ch;
17751775
}
@@ -1799,6 +1799,11 @@ pure fn char_range_at_reverse(ss: &str, start: uint) -> CharRange {
17991799
return CharRange {ch:ch, next:prev};
18001800
}
18011801

1802+
/// Plucks the `n`th character from the end of a string
1803+
pub pure fn char_at_reverse(s: &str, i: uint) -> char {
1804+
char_range_at_reverse(s, i).ch
1805+
}
1806+
18021807
/**
18031808
* Loop through a substring, char by char
18041809
*
@@ -2274,6 +2279,7 @@ pub trait StrSlice {
22742279
pure fn to_owned(&self) -> ~str;
22752280
pure fn to_managed(&self) -> @str;
22762281
pure fn char_at(&self, i: uint) -> char;
2282+
pure fn char_at_reverse(&self, i: uint) -> char;
22772283
fn to_bytes(&self) -> ~[u8];
22782284
}
22792285
@@ -2419,6 +2425,11 @@ impl StrSlice for &'self str {
24192425
#[inline]
24202426
pure fn char_at(&self, i: uint) -> char { char_at(*self, i) }
24212427
2428+
#[inline]
2429+
pure fn char_at_reverse(&self, i: uint) -> char {
2430+
char_at_reverse(*self, i)
2431+
}
2432+
24222433
fn to_bytes(&self) -> ~[u8] { to_bytes(*self) }
24232434
}
24242435
@@ -3426,6 +3437,28 @@ mod tests {
34263437
}
34273438
}
34283439

3440+
#[test]
3441+
fn test_char_at() {
3442+
let s = ~"ศไทย中华Việt Nam";
3443+
let v = ~['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
3444+
let mut pos = 0;
3445+
for v.each |ch| {
3446+
fail_unless!(s.char_at(pos) == *ch);
3447+
pos += from_char(*ch).len();
3448+
}
3449+
}
3450+
3451+
#[test]
3452+
fn test_char_at_reverse() {
3453+
let s = ~"ศไทย中华Việt Nam";
3454+
let v = ~['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
3455+
let mut pos = s.len();
3456+
for v.each_reverse |ch| {
3457+
fail_unless!(s.char_at_reverse(pos) == *ch);
3458+
pos -= from_char(*ch).len();
3459+
}
3460+
}
3461+
34293462
#[test]
34303463
fn test_each_char() {
34313464
let s = ~"abc";

0 commit comments

Comments
 (0)