Changeset 1349

Show
Ignore:
Timestamp:
11/29/09 20:10:18 (9 months ago)
Author:
andrei
Message:

Optimization in replace: if the searched string is not found, return the original string

Files:

Legend:

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

    r1319 r1349  
    18411841    r[width - s.length .. width] = s; 
    18421842    return assumeUnique(r); 
    18431843} 
    18441844 
    18451845/******************************************** 
    18461846 * Replace occurrences of from[] with to[] in s[]. 
    18471847 */ 
    18481848 
    18491849string replace(string s, string from, string to) 
    18501850{ 
     1851    if (from.length == 0) return s; 
     1852 
    18511853    char[] p; 
    1852     int i; 
    1853     size_t istart; 
    1854  
    1855     //printf("replace('%.*s','%.*s','%.*s')\n", s, from, to); 
    1856     if (from.length == 0) 
    1857     return s; 
    1858     istart = 0; 
    1859     while (istart < s.length) 
    1860     { 
    1861         i = indexOf(s[istart .. s.length], from); 
     1854    for (size_t istart; istart < s.length; ) 
     1855    { 
     1856        auto i = indexOf(s[istart .. s.length], from); 
    18621857        if (i == -1) 
    18631858        { 
     1859            if (istart == 0) 
     1860            { 
     1861                // Never found, so just return s 
     1862                return s; 
     1863            } 
    18641864            p ~= s[istart .. s.length]; 
    18651865            break; 
    18661866        } 
    18671867        p ~= s[istart .. istart + i]; 
    18681868        p ~= to; 
    18691869        istart += i + from.length; 
    18701870    } 
    18711871    return assumeUnique(p); 
    18721872} 
    18731873 
     
    18811881    string r; 
    18821882    int i; 
    18831883 
    18841884    r = replace(s, from, to); 
    18851885    i = cmp(r, "This is a silly silly list"); 
    18861886    assert(i == 0); 
    18871887 
    18881888    r = replace(s, "", to); 
    18891889    i = cmp(r, "This is a foo foo list"); 
    18901890    assert(i == 0); 
     1891 
     1892    assert(replace(r, "won't find this", "whatever") is r); 
    18911893} 
    18921894 
    18931895/***************************** 
    18941896 * Return a _string that is s[] with slice[] replaced by replacement[]. 
    18951897 */ 
    18961898 
    18971899string replaceSlice(string s, in string slice, in string replacement) 
    18981900in 
    18991901{ 
    19001902    // Verify that slice[] really is a slice of s[]