Skip to content

Commit 14baf88

Browse files
committed
core::str: added index (char)
1 parent a131b43 commit 14baf88

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/libcore/str.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -870,6 +870,30 @@ fn lines_iter(ss: str, ff: fn(&&str)) {
870870
Section: Searching
871871
*/
872872

873+
// Function: index
874+
//
875+
// Returns the index of the first matching char
876+
// (as option some/none)
877+
fn index(ss: str, cc: char) -> option<uint> {
878+
let bii = 0u;
879+
let cii = 0u;
880+
let len = byte_len(ss);
881+
while bii < len {
882+
let {ch, next} = char_range_at(ss, bii);
883+
884+
// found here?
885+
if ch == cc {
886+
ret option::some(cii);
887+
}
888+
889+
cii += 1u;
890+
bii = next;
891+
}
892+
893+
// wasn't found
894+
ret option::none;
895+
}
896+
873897
/*
874898
Function: index
875899
@@ -1448,6 +1472,9 @@ mod tests {
14481472
assert (index_byte("hello", 'e' as u8) == 1);
14491473
assert (index_byte("hello", 'o' as u8) == 4);
14501474
assert (index_byte("hello", 'z' as u8) == -1);
1475+
assert (index("hello", 'e') == option::some(1u));
1476+
assert (index("hello", 'o') == option::some(4u));
1477+
assert (index("hello", 'z') == option::none);
14511478
assert (rindex_byte("hello", 'l' as u8) == 3);
14521479
assert (rindex_byte("hello", 'h' as u8) == 0);
14531480
assert (rindex_byte("hello", 'z' as u8) == -1);

0 commit comments

Comments
 (0)