I have a string like this- 11/15/2013. I want to replace 2013 with 2000 (last 2 digits with 0). how to do this?
Asked
Active
Viewed 176 times
-2
-
`String.replace(...)` ? – Neet Nov 15 '13 at 14:39
-
google: http://stackoverflow.com/questions/1234510/how-do-i-replace-a-character-in-a-string-in-java – Fabinout Nov 15 '13 at 14:40
-
but what are the parameters within (...)? Is there any direct way to replace string by index? – G.Madri Nov 15 '13 at 14:43
-
2Maybe it's just me, but it seems you should learn a little about the language you are programming in. I hope these are homework problems and you aren't getting paid for this... I suggest you bookmark this: http://docs.oracle.com/javase/7/docs/api/ and make it your FIRST stop when you run into a problem. We are glad to help with legitmate problems, but not trivial stuff. And your rep will take fewer hits... – WPrecht Nov 15 '13 at 14:44
-
It's worth noting that strings are immutable (cannot be changed) as such you will actually get a new string with those characters changed – Richard Tingle Nov 15 '13 at 14:50
5 Answers
5
You can always do replace date.replace("13", "00");
but if you are looking at something generic of a solution (In case if you are not aware of what the last 2 digits are, yet you want them to be '00') you can do something like this :
String date = "11/15/2013";
String newDate = date.substring(0,8)+"00";
Or you can use a StringBuilder:
StringBuilder date = new StringBuilder("11/15/2013");
date.setCharAt(8, '0');
date.setCharAt(9, '0');
or
StringBuilder date = new StringBuilder("11/15/2013");
date.replace(8, 10, "00");

codeMan
- 5,730
- 3
- 27
- 51
-
-
@G.Madri if it is useful please accept it, so that it will be helpful for others too. – codeMan Nov 15 '13 at 14:56
1
code snippet
String date = "11/15/2013";
String replaced = date.replace("2013","2000");

RamonBoza
- 8,898
- 6
- 36
- 48
1
If you really want to replace a sequence at a certain index of a String
, use a StringBuilder
:
String replaced = new StringBuilder(date)
.replace(8, 10, "00").toString();

isnot2bad
- 24,105
- 2
- 29
- 50
-
I'm getting the system time and replace it's year by 2000. So I don't know the year of the system time.This is what I really wanted :) – G.Madri Nov 15 '13 at 14:49
-
1Fine. Sidenote: Make sure that the position of the year never changes - i.e. day and month should always be two digits (e.g. "07/03" for 7th of march). – isnot2bad Nov 15 '13 at 14:59
1
String date = "11/15/2013";
System.out.println(date.substring(0, date.length()-2).concat("00"));
Is this what you are looking for?

Punit
- 33
- 7