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.
Replace()
changes the first, but also all following matching instances in the source string
. A new string
is returned containing the modifications.
Replace
exampleTo 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."
// 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
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.
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
The string
type in F# offers other methods that change strings. For example, Insert
and Remove
are similar to Replace
.
string
operationStrings 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.