全部替换+ - [英] replace all + with -

查看:85
本文介绍了全部替换+ - 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 + 字符替换为我的字符串中的连字符

I am trying to replace a + character into a hyphen I have in my string.

String str = "word+word";
str.replaceAll('+ ', '-');

我尝试使用替换,但它抛出异常。还有其他方法可以做到这一点。

I tried using replace but it throwing an exception.Is there any other method to do this.

推荐答案

只需使用替换

str = str.replace('+', '-');

这个在正则表达式上不起作用,但按原样使用字符。

另外如您所见,您必须再次将值重新计入您的 str 变量,因为 String 在Java中是不可变的。在这种情况下,方法 replace 不会更改当前字符串 str )但创建一个新的替换 + 为' - '。

This one doesn't work on regex but take characters as they are.
Also as you see you have to reassing value again to your str variable because String in Java are immutable. In this case method replace doesn't change current String (str) but create new one with replaced + to '-'.

这篇关于全部替换+ - 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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