已弃用警报:Stdlib.String.set

  • 本文关键字:Stdlib String set ocaml
  • 更新时间 :
  • 英文 :


以下代码返回错误,并指出语法已弃用。更改字符串中字符的正确方法是什么?

let hello = "Hello!" ;;
hello.[1] <- 'a' ;;
Alert deprecated: Stdlib.String.set
Use Bytes.set instead.
Error: This expression has type string but an expression was expected of type
bytes

字符串是不可变的(或者至少很快它们会是不可变的(,因此您无法更改其内容。当然,您可以创建一个字符串的副本,其中一个字符不同,例如,

let with_nth_char m c = 
String.mapi (fun i b -> if i = m then c else b)

# with_nth_char 1 'E' "hello";;
- : string = "hEllo"

但是,如果您需要更改数组中的字符,则不应使用string数据类型,而应依赖bytes这是一种可变字符串的类型。 您可以使用Bytes.of_stringsBytes.to_string将字符串转换为字节,反之亦然。

最新更新