Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #116 Remove occurrences of word from string

Remove all occurrences of string w from string s1, and store the result in s2.

String s2 = s1.replace(w, "");
(def s2 (clojure.string/replace s1 w ""))
string s2 = s1.Replace(w, string.Empty);
import std.array;
auto s2 = s1.replace(w, "");
var s2 = s1.replaceAll(w,"");
s2 = String.replace(s1, w, "")
S2 = string:replace(S1, W, "", all).
  character(len=:), allocatable :: s1
  character (len=:), allocatable :: s2

  character(len=:), allocatable :: w
  integer :: i, j, k, tc

  allocate (s2, mold=s1)
  i = 1
  j = 1
  do
     k = index (s1(i:), w)
     if (k == 0) then
        s2(j:j+len(s1)-i) = s1(i:)
        s2 = s2(:j+len(s1)-i)
        exit
     else
        tc = k - 1
        if (tc > 0) s2(j:j+tc-1) = s1(i:i+tc-1)
        i = i + tc + len(w)
        j = j + tc
     end if
  end do
import "strings"
s2 := strings.ReplaceAll(s1, w, "")
import "strings"
s2 := strings.Replace(s1, w, "", -1)
import Data.List (isPrefixOf)
remove :: String -> String -> String
remove w "" = ""
remove w s@(c:cs) 
  | w `isPrefixOf` s = remove w (drop (length w) s)
  | otherwise = c : remove w cs

s2 = remove w s1
var regex = RegExp(w, 'g');
var s2 = s1.replace(regex, '');
const s2 = s1.split(w).join('')
s2 = s1:gsub(w,"")
$s2 = str_replace($w, '', $s1);
uses Sysutils;
s2 := s1.Replace(w,''.Empty);
uses Sysutils;
s2 := s1.Replace(w,'');
Uses sysutils;
s2 := stringreplace(s1, w, '', [rfReplaceAll]);
use 5.014;
my $s2 = $s1 =~ s/\Q$w//gr;
s2 = s1.replace(w, '')
s2 = s1.gsub(w, "")
s2 = s1.replace(w, "");
let s2 = str::replace(s1, w, "");
Dim s2 As String = s1.Replace(w, String.Empty)

New implementation...
< >
programming-idioms.org