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,517
  • 11
  • 65
  • 125
Ibnu Habibie
  • 721
  • 1
  • 9
  • 20

2 Answers2

1
public String getEmailParsing(String email){
    return email.replaceAll("[@.]+","_");
}
Rohit Sharma
  • 13,527
  • 7
  • 56
  • 70
Prashant Jajal
  • 3,226
  • 4
  • 22
  • 36
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
  • 13,136
  • 6
  • 29
  • 38