| Author |
Unable to read the string properly
|
Karthik Sanyasi
Greenhorn
Joined: Sep 24, 2010
Posts: 2
|
|
Hi,
When I'm trying to replace a particular character "\" in the String to "/". It gives me a different output as "02?0" for my program. After browsing I understood that this character "\" while reading, java reads it like an escaped character.
So can anyone help me in this that gives me the resulting output as "02/13/2010"
public class StringToDate {
public static void main(String[] args) {
String s = "02\13\2010";
String str = s.replace("\\","/");
System.out.println(str);
}
}
Output is: 02?0
The Output that I'm expecting is : 02/13/2010
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
That string doesn't contain any backslash characters. Print it out to see what it actually looks like. You should have this instead:
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32644
|
|
And welcome to the Ranch
|
 |
Karthik Sanyasi
Greenhorn
Joined: Sep 24, 2010
Posts: 2
|
|
Tnx Paul for the quick reply.
I see what you saying.
So basically when I'm reading a string of some text file, and if that text has 02\13\2010 then the string reads it like 02\\13\\2010. If that's your point then what's the way that I can replace that character to "/" and get my resulting output as 02/13/2010.
I tried it like as you said but still I get the output as "02\13\2010" and not "02/13/2010"
Output s1: 02?0
Output s2: 02\13\2010
Output s3: 02?0
Output s4: 02\13\2010
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32644
|
|
|
Please use the code button; since you are new I have edited your post and you can see how much better it looks.
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
Karthik Sanyasi wrote:So basically when I'm reading a string of some text file, and if that text has 02\13\2010 then the string reads it like 02\\13\\2010. If that's your point then what's the way that I can replace that character to "/" and get my resulting output as 02/13/2010.
No when you read 02\13\2010 from an input source the String will contain 02\13\2010. However when you use a String literal in your code then you need to escape the backslashes. So that becomes:
String s = "02\\13\\2010";
|
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
|
 |
Shanky Sohar
Ranch Hand
Joined: Mar 17, 2010
Posts: 1046
|
|
|
Welcome to JavaRanch.
|
SCJP6.0,My blog Ranchers from Delhi
|
 |
 |
|
|
subject: Unable to read the string properly
|
|
|