@@ -420,7 +420,54 @@ class Str {
420
420
return maxlen;
421
421
}
422
422
423
- // / rmoves the indicated substring from the string
423
+ // / Replaces the first instance of toReplace with replaced
424
+ virtual bool replace (const char * toReplace, const char * replaced){
425
+ bool result = false ;
426
+ if (toReplace==nullptr ||replaced==nullptr ){
427
+ return result;
428
+ }
429
+ if (!isConst ()){
430
+ int pos = indexOf (toReplace);
431
+ int old_len = length ();
432
+ int insert_len =0 ;
433
+ if (pos>=0 ){
434
+ int len_replaced = strlen (replaced);
435
+ int len_to_replace = strlen (toReplace);
436
+ insert_len = len_replaced-len_to_replace;
437
+ grow (this ->length ()+insert_len);
438
+ // save remainder and create gap
439
+ memmove (this ->chars +pos+len_replaced, this ->chars +pos+len_to_replace, old_len-pos+len_to_replace+1 );
440
+ // move new string into gap
441
+ memmove (this ->chars +pos,replaced,len_replaced);
442
+ result = true ;
443
+ len += insert_len;
444
+ }
445
+ }
446
+ return result;
447
+ }
448
+
449
+ // / Replaces all instances of toReplace with replaced
450
+ virtual bool replaceAll (const char * toReplace, const char * replaced){
451
+ if (indexOf (toReplace)==-1 ){
452
+ return false ;
453
+ }
454
+ while (replace (toReplace,replaced));
455
+ return true ;
456
+ }
457
+
458
+ // / removes the indicated substring from the string
459
+ virtual void remove (const char * toRemove){
460
+ if (!isConst () && chars!=nullptr ){
461
+ int removeLen = strlen (toRemove);
462
+ int pos = indexOf (toRemove);
463
+ if (pos>=0 ){
464
+ memmove ((void *) (chars+pos), (void *) (chars+pos+removeLen), len - (pos + removeLen)+1 );
465
+ len -= removeLen;
466
+ }
467
+ }
468
+ }
469
+
470
+ // / removes the indicated substring from the string
424
471
virtual void removeAll (const char * toRemove){
425
472
if (!isConst () && chars!=nullptr ){
426
473
int removeLen = strlen (toRemove);
0 commit comments