| Author |
change a string
|
david lightman
Ranch Hand
Joined: Nov 03, 2004
Posts: 82
|
|
I have a strings that comes in always as STRING1.CAT, STRING2.CAT., STRING3.CAT, but I want to convert each one to STRING1.DOG, STRING2.DOG, STRING3.DOG. I know that each string will ALWAYS begin with 8 places(STRING#. then the last three. so should i place this is a string buffer and and change cat to dog? how?
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
|
How about using the replaceAll(String, String) method of the String class?
|
JavaRanch FAQ HowToAskQuestionsOnJavaRanch
|
 |
david lightman
Ranch Hand
Joined: Nov 03, 2004
Posts: 82
|
|
String dStr = cStr.replaceAll(cStr, "CAT", "DOG"); i see the method, but me being a newbie, how exactly would I execute? thanks again
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
|
Pretty much as you have written it. You only have to worry if "CAT" can exist anywhere else in your string...
|
 |
david lightman
Ranch Hand
Joined: Nov 03, 2004
Posts: 82
|
|
think I've got it. thanks. [ April 11, 2005: Message edited by: david lightman ]
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 10043
|
|
Because my wife calls me "Captain Literal", i feel obligated to point something out. You are not really changing the string here. cStr remains what it always was. What you are doing is createding a NEW string, based off the original, and creating a new reference to it. you could do cStr = cStr.replaceAll("CAT", "DOG"); but again, this creates a new string, and re-assigns the cStr referenct to point to the new one. [edited to correct the call, per Ernest's note below] [ April 11, 2005: Message edited by: fred rosenberger ]
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
And because of my ongoing fight for truth, justice, and the American way, I need to point out that the first argument y'all keep sticking in there doesn't belong. It's just cStr = cStr.replaceAll("CAT", "DOG");
|
[Jess in Action][AskingGoodQuestions]
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 10043
|
|
Again, i failed to completly read the posts. i plead guilty to just cut-n-pasting others errors, though i know that is a poor excuse. <hangs head in shame>
|
 |
Jeff Jetton
Ranch Hand
Joined: Mar 29, 2005
Posts: 71
|
|
You know, since the input strings are always going to be in the same format, the following would probably be more efficient: - Jeff
|
 |
 |
|
|
subject: change a string
|
|
|