strreplace

Purpose

Replace all matches of a substring with a replacement string.

Format

str_new = strreplace(str, search, replace)
Parameters:
  • str (string) – to be searched and modified.
  • search (string) – the substring to search for in str.
  • replace (string) – the substring with which to replace all instances of search found in str.
Returns:

str_new (string) – new string which is the same as str, except that all instances of search have been replaced with replace.

Examples

Basic search and replace

// String to be searched in
str = "My doctor recommends more chocolates, because chocolates are healthy.";

// String to be searched for
search = "chocolate";

// String to be replaced with
replace = "vegetable";

// Build new string
new_str = strreplace(str, search, replace);

After the code above, new_str will be set to:

My doctor recommends more vegetables, because vegetables are healthy.

Regularize addresses in string array

// String array to be searched
str = "100 Main Ave" $|
      "112 Charles Avenue" $|
      "49 W State St" $|
      "24 Third Avenue";

// String to search for
search = "Avenue";

// String to replace with
replace = "Ave";

// Build new string
new_str = strreplace(str, search, replace);

After the code above, new_str will be set to:

   "100 Main Ave"
"112 Charles Ave"
  "49 W State St"
   "24 Third Ave"

See also

Functions strrindx(), strsect()