📜  F#-字符串(1)

📅  最后修改于: 2023-12-03 15:15:12.696000             🧑  作者: Mango

F# - Strings

F# provides several ways to represent and manipulate strings, which are sequences of characters. This guide covers the basics of working with strings in F#.

Creating Strings

Strings can be created in F# using string literals, like "hello world". F# also provides a string constructor that can be used to create strings from character arrays:

let s1 = "hello world"
let s2 = string [| 'h'; 'e'; 'l'; 'l'; 'o'; ' '; 'w'; 'o'; 'r'; 'l'; 'd' |]
String Concatenation

Strings in F# can be concatenated using the ^ operator or the String.Concat function:

let s1 = "hello"
let s2 = "world"
let s3 = s1 ^ " " ^ s2
let s4 = String.Concat([|s1; " "; s2|])
Formatting Strings

F# provides several ways to format strings. The easiest way is to use string interpolation:

let name = "Alice"
let age = 30
let message = $"{name} is {age} years old"

F# also provides the sprintf function, which is similar to printf but returns a string instead of printing to the console:

let name = "Bob"
let age = 40
let message = sprintf "%s is %d years old" name age
String Manipulation

F# provides several functions for manipulating strings. Here are some examples:

let s1 = "hello world"
let length = String.length s1
let substring = String.sub s1 6 5 // "world"
let contains = String.contains s1 "world"
let replace = String.replace "hello" "hi" s1 // "hi world"
let split = s1.Split([|' '|]) // ["hello"; "world"]
Conclusion

In this guide, we covered the basics of working with strings in F#. For more information, see the official documentation.