C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: We perform another replacement. We replace "and" with "or." All 3 strings are independent—strings are not modified in-place.
F# program that uses Replace
// Our initial string.
let animals = "cats and dogs and fish"
// Change "cats" to "birds."
let result1 = animals.Replace("cats", "birds")
// Change another word.
// ... All instances of the substring are replaced.
let result2 = result1.Replace("and", "or")
// The three strings are separate.
printfn "%s" animals
printfn "%s" result1
printfn "%s" result2
Output
cats and dogs and fish
birds and dogs and fish
birds or dogs or fish
F# program that uses Replace with char argument
let code = "abcdefabc"
// Use Replace to change letter "a" to underscore.
let result = code.Replace('a', '_')
printfn "%s" code
printfn "%s" result
Output
abcdefabc
_bcdef_bc
Here: We change the colon character to a lowercase letter "A." Please note multiple replacements could occur in the loop body.
Result: We convert the array to a new string with the string constructor. Our replacement is complete.
F# program that uses ToCharArray, for loop, replaces char
let name = ":reop:gitic:"
// Convert string to an array.
let array = name.ToCharArray()
// Change colon character to letter "A" in string.
for c in 0 .. array.Length - 1 do
if array.[c] = ':' then
array.[c] <- 'a'
// Convert char array to string.
let resultCopy = new string(array)
printfn "%s" resultCopy
Output
areopagitica