|
|
The first example is a function to replace all instances of a String
pattern
in an input String in_Str
with a String rep
.
String replace(String in_Str, String pattern, String rep) { int i = in_String.index(pattern); if( i < 0) return in_Str; int plen = length(pattern); int rlen = length(rep); int j; do { in_Str(i, plen) = rep; i += rlen; String rest = in_Str(i, length(in_Str)-i); i += (j = rest.index(pattern)); } while(j >= 0); return in_Str; }
The replace
routine uses the function
index
to find all occurrences of
pattern
in the String in_Str
and replace each occurrence with the String
rep
.
Replace can be used to write a simple sed-like program as follows:
main(int argc,char *argv[]) { String in_Str; String rslt; while( gets(in_String) ) { String rslt = replace(in_Str,argv[1],argv[2]); cout << rslt << "\\n"; } }