如何在Dart中将字符串转换为原始字符串 [英] How to convert string to raw string in dart

查看:75
本文介绍了如何在Dart中将字符串转换为原始字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将现有字符串转换为原始字符串.

点赞:

String s = "Hello \n World"

我想将此s变量转换为原始字符串(我想打印确切的"Hello \ n Wrold")

I want to convert this s variable to raw string(I want to print exact "Hello \n Wrold")

我在输出中需要反斜杠(\).我正在尝试从rest api获取字符串值.它有一堆包含反斜杠的mathjax(latex)公式.

谢谢

推荐答案

您正在寻求一种以字符串值换行换行符(以及其他控制字符)的方法.

You are asking for a way to escape newlines (and possibly other control characters) in a string value.

在平台库中没有通用的方法可以对Dart字符串执行此操作,但是在大多数情况下,请使用

There is no general way to do that for Dart strings in the platform libraries, but in most cases, using jsonEncode is an adequate substitute.

因此,鉴于您的 string 包含换行符,您可以将其转换为包含 \ n 的字符串(反斜杠和 n )作为 var escapedString = jsonEncode(string); .结果也用双引号引起来,因为它实际上是JSON字符串文字.如果不希望这样,则可以删除第一个和最后一个字符: escapedString = escapedString.substring(1,escapedString.length-1); .

So, given your string containing a newline, you can convert it to a string containing \n (a backslash and an n) as var escapedString = jsonEncode(string);. The result is also wrapped in double-quotes because it really is a JSON string literal. If you don't want that, you can drop the first and last character: escapedString = escapedString.substring(1, escapedString.length - 1);.

或者,如果您只关心换行符,则可以自己替换它们:

Alternatively, if you only care about newlines, you can just replace them yourself:

var myString = string.replaceAll("\n", r"\n");

这篇关于如何在Dart中将字符串转换为原始字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆