如何在java中将反斜杠插入到我的字符串中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20138363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:26:10  来源:igfitidea点击:

How to insert backslash into my string in java?

javastring

提问by AndroidDev

I have string, and I want to replace one of its character with backslash \

我有字符串,我想用反斜杠 \ 替换它的一个字符

I tried the following, but no luck.

我尝试了以下方法,但没有运气。

engData.replace("'t", "\'t")

and

engData = engData.replace("'t", String.copyValueOf(new char[]{'\', 't'}));

INPUT : "can't"

输入:“不能”

EXPECTED OUTPUT : "can\'t"

预期输出:“不能”

Any idea how to do this?

知道如何做到这一点吗?

采纳答案by Amit Gupta

Try like this

像这样尝试

engData.replace("'", "\\'");

INPUT : can't

输入:不能

EXPECTED OUTPUT : can\'t

预期输出:不能

回答by yamafontes

The following works for me:

以下对我有用:

class Foobar {
  public static void main(String[] args) {
    System.err.println("asd\'t".replaceAll("\'t", "\\'t"));
  }
}

回答by Vinith

For String instances you can use, str.replaceAll()will return a new String with the changes requested:

对于您可以使用的 String 实例,str.replaceAll()将返回一个带有请求更改的新字符串:

String str = "./";
String s_modified = s.replaceAll("\./", "");

回答by SudoRahul

Stringis immutable in Java. You need to assign back the modified string to itself.

String在 Java 中是不可变的。您需要将修改后的字符串分配回自身。

engData = engData.replace("'t", "\'t"); // assign the modified string back.

回答by Justin

This is possible with regex:

这可以通过正则表达式实现

engData = engData.replaceAll("('t)","\\");

The (and )specify a group. The 'twill match any string containing 't. Finally, the second part replaced such a string with a backslash character: \\\\(four because this), and the first group: $1. Thus you are replacing any substring 'twith \'t

()指定。该't会匹配任何字符串't。最后,第二部分用反斜杠字符替换了这样的字符串:(\\\\四个因为this),以及第一组:$1。因此,您将任何子字符串替换't\'t



The same thing is possible without regex, what you tried (see thisfor output):

没有正则表达式,同样的事情是可能的,你尝试了什么(见这个输出):

engData = engData.replace("'t","\'t"); //note the assignment; Strings are immutable

See String.replace(CharSequence, CharSequence)

String.replace(CharSequence, CharSequence)

回答by prime

Try this..

尝试这个..

    String s = "can't";
    s = s.replaceAll("'","\\'");
    System.out.println(s);

out put :

输出 :

    can\'t

This will replace every ' occurences with \' in your string.

这将在您的字符串中用 \' 替换每个 ' 出现。