HomeSearch

F# Replace String Examples

Replace. Programs spend their time modifying strings. A string contains the name of an animal. We want it to be the name of a plant. With Replace we handle this.
Initial example. Here we have a string containing the names of some animals. We replace a substring with the Replace method. 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.

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
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.
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
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.Array

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
Some notes. The string type in F# offers other methods that change strings. For example, Insert and Remove are similar to Replace.String
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.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.