Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can I delete a substring?

 
Fritz Largosa
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a string "dog,cat,tree" I want to delete cat so it becomes "dog,tree". the replace function of string only accepts a char so method String_Object.replace(char,char) is not compatible with what I need which is a String_Object.replace(String,String). Any other alternative functions I can use?
 
Seb Mathe
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a function String#replaceAll(String, String) since JDK 1.4.

Otherwise, you can use indexOf and substring methods
 
fred rosenberger
lowercase baba
Bartender
Posts: 12123
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
be carefull with strings. remember that you can't change a string once it is created.

your manipulation will create a NEW string, and unless you assign your reference to it, it will be lost.

in other words, if you do something like

String myString = new String("fred");
myString.toUpperCase();
System.out.println(myString);

the output will be "fred".

but if you do

myString = myString.toUpperCase();
System.out.println(myString);


you'll get "FRED".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic