Movatterモバイル変換


[0]ホーム

URL:


How to replace characters and substring in Java? String.replace(), replaceAll() and replaceFirst() Example

One of the common programming tasks is to replace characters or substring from a String object in Java. For example, you have a String "internet" and you want to replace the letter"i" with the letter"b", how do you that? Well, the String class in Java provides several methods to replace characters,CharSequence,and substring from a String in Java. You can call replace method on the String, where you want to replace characters and it will return a result where characters are replaced. What is the most important point to remember is that the result object would be a new String object? 

SinceString is immutable in Java, every time you perform an operation on String either replacement or removing white space from String, it generates a new String object. The good thing about these methods is that they support regular expression, which means you can specify a pattern and all the characters which match the pattern will be replaced. 

There are four overloaded method to replace String in Java :

  • replace(char oldChar, char newChar)
  • replace(CharSequence target, CharSequence replacement)
  • replaceAll(String regex, String replacement)
  • replaceFirst(String regex, String replacement)

Out of these, 2nd one which takes aCharSequence is added on Java 1.5.CharSequence is actually a super interface for String, StringBuffer and StringBuilder in Java, which means you can pass any ofString,StringBuffer orStringBuilder Object as an argument to this replace method. 

ThereplaceFirst() andreplaceAll() are very powerful and accepts regular expression.replaceFirst() only replace first match, whilereplaceAll replaces all matches with replacement String provided.



How to replace character or substring in Java? replace() example

In this Java tutorial, we will see How to replace characters and substring from String in Java. First example in this program replaces a character, i.e. it replaces"J" with"K", which creates"Kava" from"Java". SecondString replace example, replaces words from String, it replaces Scala with Java. 

Third and fourth example showshow to use regular expression to replaceString in Java. Both examples uses\\s to match spaces or any white space character and replace with#

How to replace characters on String in Java? String.replace(), replaceAll() and replaceFirst() Example


Third one usesreplaceFirst() which only replace first match, while fourth one usesreplaceAll() which replaces all matches.

packagetest;/** * Java program to replace String in Java using regular expression. * This examples examples how to replace character and substring from String in Java. * *@author Javin Paul */publicclassStringReplace {publicstaticvoidmain(Stringargs[]) {String word="Java";//replacing character in this StringString replaced= word.replace("J","K");System.out.println("Replacing character in String");System.out.println("Original String before replace : "+ word);System.out.println("Replaced String : "+ replaced);//replacing substring on String in JavaString str="Scala is good programming language";     replaced= str.replaceAll("Scala","Java");System.out.println("String before replace : "+ str);System.out.println("String after replace : "+ replaced);//replacing all space in String with # using regular expression     replaced= str.replaceFirst("\\s","#");System.out.println("Replacing first match of regex using replaceFirst()");System.out.println("Original String before replacement : "+ str);System.out.println("Final String : "+ replaced);System.out.println("Replacing all occurrence of substring which match regex");     replaced= str.replaceAll("\\s","#");System.out.println("ReplaceAll Example : "+ replaced);    }    }Output:Replacing character inStringOriginalString before replace:JavaReplacedString:KavaString before replace:Scala is good programming languageString after replace:Java is good programming languageReplacing first match of regex using replaceFirst()OriginalString before replacement:Scala is good programming languageFinalString:Scala#is good programming languageReplacing all occurrence of substring which match regexReplaceAllExample:Scala#is#good#programming#language

That's it onHow to replace String in Java. As explainedjava.lang.String class provides multipleoverloaded methods, which can replace a single character or substring in Java.replaceAll() in particular is very powerful and can replace all occurrences of any matching character or regular expression in Java.

It also expects a regular expression pattern, which provides it more power. You can use this method to say replace all commas with pipe to convert a comma-separated file to a pile delimited String. If you just want to replace one character, just use replace() method, which takes two characters, the old and new characters. 


RelatedJava String Tutorials from Java67 Blog


4 comments:

  1. I am definitely going to attend the Java One again. Last time I had a chance to help people at NetBeans Booth, thanks to Java One Team for that great favor. I know, Java and NetBeans community will definitely attend this prestigious nd great conference this year too…..
    You all can Sign up here https://www.regpulse.com/javaone2013/register.php?pcode=737266&src=4003&Act=1 to find out more details and launch date for the 2013 JavaOne. JavaOne India 2013 goin to happen on 8-9 May in Hyderabad at the same place as last year guys….

    ReplyDelete
  2. absolutely amazing. Thanks :)

    ReplyDelete
  3. Hi, I just would like to ask. Is there any alternative in changing characters or words without using the replace function? Maybe using a loop and conditional statement? Thanks :)

    ReplyDelete
    Replies
    1. yes, you can replace by changing characters directly in character array, it will become problem of replacing character in array then.

      Delete

Feel free to comment, ask questions if you have any doubt.


[8]ページ先頭

©2009-2025 Movatter.jp