Java替換方法,替換為空字符[重復]

[英]Java replace method, replacing with empty character [duplicate]


This question already has an answer here:

這個問題已經有了答案:

Suppose I have the following in String format:

假設我有以下字符串格式:

2.2

2.2

And I want to replace the decimal point with an empty space, to make it look like this:

我想用一個空的空間來替換小數點,讓它看起來像這樣:

22

22

How do I do this? I thought replace would have done the trick, but when I try it like this:

我該怎么做呢?我原以為“替換”會奏效,但當我這樣嘗試的時候:

string.replace('.', '');

. replace('。’”);

I get an error with the '' because it supposedly isn't a character. That makes sense, so how else can I accomplish what I want?

我有一個錯誤,因為它應該不是一個字符。這是有道理的,那么我怎么才能實現我想要的呢?

2 个解决方案

#1


21  

If you just exchange single for double quotes, this will work because an empty string is a legal value. It seems that many people overlook the fact that replace(CharSequence, CharSequence) actually works on string arguments :)

如果您只交換單引號,這將有效,因為空字符串是一個合法值。許多人似乎忽視了以下事實:replace(CharSequence, CharSequence)實際上可以處理字符串參數:

#2


11  

try :

試一試:

string.replace(".", "");

Other way is to use replaceAll :

另一種方法是使用replaceAll:

string.replaceAll("\\.","");

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/11/03/72f387b0a1796fadd770a2b3947b8685.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com