@@ -908,6 +908,39 @@ fn find(haystack: str, needle: str) -> int {
908
908
ret -1 ;
909
909
}
910
910
911
+ // Function: find_chars
912
+ //
913
+ // Find the character position of the first instance of the substring,
914
+ // or return option::none
915
+ //
916
+ // FIXME: rename find_chars -> find,
917
+ // find -> find_bytes
918
+ fn find_chars ( hay : str , pin : str ) -> option < uint > {
919
+ alt find ( hay, pin) {
920
+ -1 { ret option:: none; }
921
+ n { ret option:: some ( b2c_pos ( hay, n as uint ) ) ; }
922
+ }
923
+ }
924
+
925
+ // Function: b2c_pos
926
+ //
927
+ // Convert a byte position into a char position
928
+ // within a given string
929
+ fn b2c_pos ( ss : str , bpos : uint ) -> uint {
930
+ assert bpos < len_bytes ( ss) ;
931
+
932
+ let ii = 0 u;
933
+ let cpos = 0 u;
934
+
935
+ while ii < bpos {
936
+ let sz = utf8_char_width ( ss[ ii] ) ;
937
+ ii += sz;
938
+ cpos += 1 u;
939
+ }
940
+
941
+ ret cpos;
942
+ }
943
+
911
944
/*
912
945
Function: contains
913
946
@@ -1718,6 +1751,23 @@ mod tests {
1718
1751
assert ( find ( data, "ไท华" ) == -1 ) ;
1719
1752
}
1720
1753
1754
+ #[ test]
1755
+ fn test_find_chars ( ) {
1756
+ let data = "ประเทศไทย中华Việt Nam" ;
1757
+ assert ( find_chars ( data, "ประเ" ) == option:: some ( 0 u) ) ;
1758
+ assert ( find_chars ( data, "ะเ" ) == option:: some ( 2 u) ) ;
1759
+ assert ( find_chars ( data, "中华" ) == option:: some ( 9 u) ) ;
1760
+ assert ( find_chars ( data, "ไท华" ) == option:: none) ;
1761
+ }
1762
+
1763
+ #[ test]
1764
+ fn test_b2c_pos ( ) {
1765
+ let data = "ประเทศไทย中华Việt Nam" ;
1766
+ assert 0 u == b2c_pos ( data, 0 u) ;
1767
+ assert 2 u == b2c_pos ( data, 6 u) ;
1768
+ assert 9 u == b2c_pos ( data, 27 u) ;
1769
+ }
1770
+
1721
1771
#[ test]
1722
1772
fn test_substr ( ) {
1723
1773
fn t ( a : str , b : str , start : int ) {
0 commit comments