Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How to use String.replaceall() method on Java me(J2ME);?

user-image
Question added by Ahmed Gamal Ahmed
Date Posted: 2015/07/06
Nasim Khan
by Nasim Khan , Business Technology Analyst , Deloitte Consulting

The function of "replaceAll" is to substitute all occurrences of a particular string in another string. Following is the syntax of this method :

 

public String replaceAll(String regex, String replacement)

 

Consider the following example for further Clarification :

 

import java.lang.*;

 

public class StringDemo {

 

   public static void main(String[] args) {

  

   String str1 = "!!ABC!!DEMO", str2;

   String substr = "**", regex = "!!";

    

   // prints string1

   System.out.println("String = " + str1);

    

   /* replaces each substring of this string that matches the given

   regular expression with the given replacement */

 

   str2 = str1.replaceAll(regex, substr);    

   System.out.println("After Replacing = " + str2);

   }

}

 

The output of the code is as follows :

 

String = !!ABC!!DEMO

After Replacing = **ABC**DEMO

 

As you can see, all the occurrences of the substr("!!") in string1 are replaced by the regex("**").

Mohammed Ersan
by Mohammed Ersan , Senior Android Developer , Mobile Travel Technologies

there is no replace all in J2ME since it uses old java1.2 (AFAIK), but here is a replacement method you can use

 

 

privateString replace(String str,String pattern,String replace ){int s =0;int e =0;StringBuffer result =newStringBuffer();while((e = str.indexOf( pattern, s ))>=0){ result.append(str.substring( s, e )); result.append( replace ); s = e+pattern.length();} result.append( str.substring( s ));return result.toString();}

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.