首页 > 解决方案 > 如何在 Nim 中回显带有转义序列的字符串?

问题描述

如果我回显这样的字符串:

let s = "Hello\nworld"
echo s

我得到:

Hello
world

我想输出: Hello\nworld

我知道如果我正在定义字符串,我可以使用原始字符串文字,但是如果字符串来自例如文件,我该怎么做?

我想我正在寻找类似于 pythonsrepr()函数的东西。

编辑:Nim 有一个 repr 功能。但是,输出不是我想要的:

let hello = "hello\nworld"
echo repr(hello)

---- Output ----
0x7fc69120b058"hello\10"
"world"

标签: nim-lang

解决方案


您可以使用 strutils 包中的转义函数。

import strutils

let s = "Hello\nWorld"
echo s.escape()

这将打印:

Hello\x0AWorld

当前的 strutils 转义函数实现将换行符转义为十六进制值。您可以使用以下代码按照 python 的方式进行操作。

func escape(s: string): string =
  for c in items(s):
    case c
    of '\0'..'\31', '\34', '\39', '\92', '\127'..'\255':
      result.addEscapedChar(c)
    else: add(result, c)

let s = "Hello\nWorld"
echo s.escape()

输出:

Hello\nWorld

这是escapeaddEscapeChar函数的文档链接


推荐阅读