Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String Replace and Replace All methods  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

when i practicing string methods, i didn't understand difference b/w string replace and string replace All.

could you please tell me that difference and please provide sample code on string methods.
 
lowercase baba
Bartender
Posts: 12613
50
Chrome Java Linux
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you read the api?

String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.



There are two 'replace' methods, and one 'replaceAll' method. the first replace method takes a SINGLE CHARACTER, and replaces it with a SINGLE CHARACTER.

The second will take a CharSequence - basically a string - and will replace it with another string (note - I used a little 's' there on purpose).

Finally, the 'replaceAll' takes a regular expression, which lets you do much more powerful substitutions, and replaces it with a String. So you could pass "r.n" and it would replace "run", "ran", or "ron" (or many other things) with what you supply.
 
Ranch Hand
Posts: 118
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
replace function replaces a single character
and replace all function replaces each occurrence of the character with a new character provided.
 
sakshi sa
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks.
 
Sheriff
Posts: 21288
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Atul Darne wrote:replace function replaces a single character


That used to be the case, but since Java 5.0 there's another one.

and replace all function replaces each occurrence of the character with a new character provided.


No it doesn't. That's what replace(char, char) does. replaceAll doesn't even replace characters; it replaces regular expressions.
 
Marshal
Posts: 58322
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sakshi sa,
Your post was moved to a new topic.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!