Skip to content

Commit fb30b74

Browse files
committed
Str::replace
1 parent 57342e6 commit fb30b74

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

src/AudioBasic/Str.h

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,54 @@ class Str {
420420
return maxlen;
421421
}
422422

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
424471
virtual void removeAll(const char* toRemove){
425472
if (!isConst() && chars!=nullptr){
426473
int removeLen = strlen(toRemove);

0 commit comments

Comments
 (0)