3

i want to replace character '@' and '.' to '_' from my string . I can replace char '.' to '_' but cant replace char '@' .

public String getemailparsing(String email){
        String result="";
        char keong = 64;
        for(int i=0; i<email.length();i++){
            if(email.charAt(i) == '@' ){
                result = email.replace('@', '_'); //this is NOT working
            }else if(email.charAt(i) == '.'){
                result = email.replace('.', '_'); //this one is working
            }
        }
        return result;
    }

any idea to replace char '@' ...

Blaze Tama
  • 10,828
  • 13
  • 69
  • 129
Ibnu Habibie
  • 721
  • 1
  • 9
  • 20

2 Answers2

1
public String getEmailParsing(String email){
    return email.replaceAll("[@.]+","_");
}
Rohit Sharma
  • 13,787
  • 8
  • 57
  • 72
Prashant Jajal
  • 3,469
  • 5
  • 24
  • 38
1

Apply the little change as shown in below code. And you will get your desired output.

public String getemailparsing(String email) {
        String result = email;

        if (email.contains("@")) {
            result = result.replace('@', '_'); 
        }
        if (email.contains(".")) {
            result = result.replace('.', '_'); 
        }
        return result;
    }
Dhrumil Shah - dhuma1981
  • 15,166
  • 6
  • 31
  • 39