Changeset 88

Show
Ignore:
Timestamp:
12/19/05 07:37:37 (3 years ago)
Author:
Don Clugston
Message:

Added meta.string.find!(), rfind!(), repeat!()

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/meta/string.d

    r83 r88  
    1313} 
    1414 
    15 /// see if character c is in the string str. 
    16 template isInString(char c, char [] str) 
     15/// int find!(char [] str, char c); 
     16/// Find first occurrence of c in string str. 
     17/// 
     18/// Returns: 
     19///   Index in s where c is found, -1 if not found.  
     20template find(char[] str, char c, int n=0) 
    1721{ 
    18   static if (str.length==0) const bool isInString=false
    19   else static if( c==str[0]) const bool isInString=true
    20   else const bool isInString = .isInString!(c, sliceheadoff!(str, 1) ); 
     22  static if (str.length==n) const int find = -1
     23  else static if( c==str[n]) const int find = n
     24  else const int find = .find!(str, c, n + 1); 
    2125} 
    2226 
     27/// int rfind!(char [] str, char c); 
     28/// Find last occurrence of c in string str. 
     29/// 
     30/// Returns: 
     31///   Index in s where c is found, -1 if not found.  
     32template rfind(char[] str, char c, int n = 0) 
     33{ 
     34  static if (str.length==n) const int rfind = -1; 
     35  else static if( c==str[str.length - n - 1]) const int rfind = str.length - n - 1; 
     36  else const int rfind = .rfind!(str, c, n + 1); 
     37} 
     38 
     39///  char [] repeat!(char [] str, uint n) 
     40/// 
     41/// Return a string that consists of s[] repeated n times. 
     42template repeat(char [] str, uint n) 
     43{ 
     44   static if (n==0) const char [] repeat=""; 
     45   else static if (n==1) const char [] repeat = str; 
     46   else const char [] repeat = str ~ .repeat!(str, n-1); 
     47} 
     48 
     49 
    2350version(testmeta) { 
    24  static assert( isInString!('r', "it's in there somewhere!")); 
    25  static assert( !isInString!('q', "but it's not in this one")); 
     51 static assert( 11 == find!("it's in there somewhere!", 'r')); 
     52 static assert( -1 == find!("but it's not in this one", 'q')); 
     53 static assert( -1 == rfind!("not in here either", 'z')); 
     54 static assert( 4 == rfind!("but this is ok", 't')); 
     55 static assert(streq!(repeat!("abc", 4), "abcabcabcabc")); 
    2656}