Compartilhar 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 8, Windows 7, Windows Server 2012, Windows Server 2008 R2Windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2

Version Information

F# Core Library VersionsF# Core Library Versions

Supported in: 2.0, 4.0, Portable2.0, 4.0, Portable

See Also

Reference

Core.String Module (F#)

Microsoft.FSharp.Core Namespace (F#)