2011-03-07 53 views
1

時間12:45 我想刪除:在java ..我只需要1245 ..我該怎麼做?刪除:在12:45(java)

+5

「12:45」.replace(「:」,「」); ? – 2011-03-07 18:36:44

+1

格式總是會變成XX:XX(其中X是數字)? – Argote 2011-03-07 18:36:56

+2

快速瀏覽一下java字符串API將解決這個問題..有替代功能。 – Voo 2011-03-07 18:37:26

回答

5
String time = "12:45".replace(":", ""); // "1245" 

如果你在你的classpath Apache Coomons Lang,而你不知道那個時候是不爲空,你可以使用StringUtils

time = StringUtils.remove(time, ":"); 

這種方式更緊湊比寫

if (time != null) { 
    time = time.replace(":", ""); 
} 
4

有「替換」方法。

s = s.replace(':',''); 

如果你想獲得幻想:

s = s.replaceAll("[^a-zA-Z0-9]", ""); 

這將刪除所有非字母數字字符(包括你的 ':')

好有在JavaDoc。

+0

我做了同樣的錯誤,s.replace(':','')將不會被編譯..'無效的字符常量' – Maxym 2011-03-07 18:41:46

+0

DOH!哦,你贏了提到StringUtils。 :) – MarkPowell 2011-03-07 19:13:52

2

如果"12:45"是一個字符串,那麼只需使用"12:45".replaceAll(":", "")

+3

'replaceAll'使用正則表達式,這將是一個矯枉過正。 'replace'應該可以正常工作。 – 2011-03-07 18:38:31

2
String strTime = "12:45"; 
strTime.replace(':',''); 
1

爲了最簡單的方法,使用替換:

String time = "12:45"; 
time = time.replace(':', ""); 

,但你可以使用正則表達式:

Pattern pattern = new Pattern("(\\d{1,2}):(\\d{1,2})"); 
Matcher matcher = pattern.matcher("12:45"); 
String noColon = matcher.group(1) + matcher.group(2); 

或字符串API:

String time = "12:45"; 
int colonIndex = time.indexOf(':"'; 
String noColon = time.substring(0, colonIndex) + 
    time.substring(colonIndex + 1, time.length); 
1

像別人說,方法越簡單Stringreplace應該足夠了,但因爲我懷疑你的輸入是一個日期,所以也請看SimpleDateFormat