Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace characters in string like in python

Tags:

crystal-lang

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?

like image 980
LavX64 Avatar asked Dec 08 '25 17:12

LavX64


1 Answers

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.

like image 120
Tim Tutt Avatar answered Dec 12 '25 15:12

Tim Tutt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!