如何将转义字符添加到Java字符串? [英] How can I add escape characters to a Java String?

查看:2112
本文介绍了如何将转义字符添加到Java字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串变量:

If I had a string variable:

String example = "Hello, I'm here";

我想在每个'前添加一个转义字符 变量(即实际转义字符),我该怎么做那个?

and I wanted to add an escape character in front of every ' and " within the variable (i.e. not actually escape the characters), how would I do that?

推荐答案

我不会在这里声称优雅,但我认为它会做你想要的它要做(请纠正我,如果我错了):

I'm not claiming elegance here, but i think it does what you want it to do (please correct me if I'm mistaken):

public static void main(String[] args)
{
    String example = "Hello, I'm\" here";
    example = example.replaceAll("'", "\\\\'");
    example = example.replaceAll("\"", "\\\\\"");
    System.out.println(example);
}

输出

Hello, I\'m\" here

这篇关于如何将转义字符添加到Java字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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