Replace. Programs spend their time modifying strings. Perhaps a string contains the name of an animal, but we want it to be the name of a plant.
String usage. Replace() changes the first, but also all following matching instances in the source string. A new string is returned containing the modifications.
Replace example. To start, we have a string containing the names of some animals. We replace a substring with Replace—the occurrences of "cats" are replaced with "birds."
Then We perform another replacement. We replace "and" with "or." All 3 strings are independent—strings are not modified in-place.
// 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" result2cats and dogs and fish
birds and dogs and fish
birds or dogs or fish
Char. The Replace method can handle a single char. All instances of the char in the string are replaced with a new char. The string's length remains the same.
let code = "abcdefabc"// Use Replace to change letter "a" to underscore.
let result = code.Replace('a', '_')
printfn "%s" code
printfn "%s" resultabcdefabc
_bcdef_bc
Character array. Sometimes a replacement is too complex to be handled with a simple Replace() call. We can convert a string to a char array, and then replace characters in a for-in loop.
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.
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" resultCopyareopagitica
Some notes. The string type in F# offers other methods that change strings. For example, Insert and Remove are similar to Replace.
A common string operation. Strings are used throughout programs. And with the Replace method from the .NET Framework, we swap string fragments in a standard, optimized way in this language.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.