Share via


String.mapi Function (F#)

Creates a new string whose characters are the results of applying a specified function to each character and index of the input string.

Namespace/Module Path: Microsoft.FSharp.Core.String

Assembly: FSharp.Core (in FSharp.Core.dll)

// Signature:
String.mapi : (int -> char -> char) -> string -> string

// Usage:
String.mapi mapping str

Parameters

  • mapping
    Type: int -> char -> char

    The function to apply to each character and index of the string.

  • str
    Type: string

    The input string.

Exceptions

Exception

Condition

ArgumentNullException

Thrown when the input string is null.

Return Value

The resulting string.

Remarks

This function is named MapIndexed in compiled assemblies. If you are accessing the function from a language other than F#, or through reflection, use this name.

Example

The following code shows how to use String.mapi.

let replaceNth n newChar inputString =
    let result = String.mapi (fun i c -> if i = n then newChar else c) inputString
    printfn "%s" result
    result
printfn "MASK"
"MASK" |> replaceNth 0 'B'
|> replaceNth 3 'H'
|> replaceNth 2 'T'
|> replaceNth 1 'O'
|> replaceNth 0 'M'
|> replaceNth 1 'A'
|> replaceNth 2 'S'
|> replaceNth 3 'K'

Output

MASK
BASK
BASH
BATH
BOTH
MOTH
MATH
MASH
MASK

Platforms

Windows 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2

Version Information

F# Runtime

Supported in: 2.0, 4.0

Silverlight

Supported in: 3

See Also

Reference

Core.String Module (F#)

Microsoft.FSharp.Core Namespace (F#)