Search code examples
crystal-lang

Replace characters in string like in python


In python there's function replace(old, new) which replaces "old" to "new" in some string, is there any function like this or any way to do it in Crystal?


Solution

  • From the Crystal-lang api docs you can use the .sub function:

    "hello yellow".sub("ll", "dd") # => "heddo yellow"
    

    Source: https://crystal-lang.org/api/0.23.1/String.html

    NOTE: This function only replaces the first occurrence of the search string. There also appears to be a version of the sub function that allows you to pass a regex string which should allow you to grab all occurrences of a particular string.