2

i have an input string , and i want to remove All char except special character(Hex Character) ! like this :

   String SpecialChar = "0123456789ABCDEF" ; // Hex Char 
   String input = "abdf%$%23%&373D^!Bfg(g)*a" ;

i want to have below output , but i get wrong value ...

   String output = "abdf23373DBfgga" ;

i write below method but it return wrong value :

private String EliminateExtra(String str) {
    String temp = str.toUpperCase(); 

    for (int i = 0 ; i < temp.length() ; i++) {
        char c = temp.charAt(i);
        if(!isHexNum(c)) {
            temp = temp.replaceAll(String.valueOf(c) , "");
        }
    }
    return temp ;
}

private Boolean isHexNum(char c) {
    char[] charArray = "0123456789ABCDEF".toCharArray();
    for(int y=0 ; y<charArray.length ; y++) {
        if(charArray[y]==c) {
            return true ;
        }
    }
    return false ;
} 

and call it like :

  String Data = "aaaDffagDDSGw!$!@$3513rX12433r1ADSfX&)&*)%(%8u4w" ;
  TextView tv = (TextView) findViewById(R.id.regex_textView1) ;
  tv.setText("Original:" + "\n" + Data.toUpperCase() + "\n" + "Result: " + "\n" + EliminateExtra(Data));
Pshemo
  • 122,468
  • 25
  • 185
  • 269
hkh114
  • 162
  • 1
  • 3
  • 15
  • notice that when you change unwanted char to "" the length of you String is changing so your for loop may skip some chars – Rafal Malek Oct 05 '15 at 12:08
  • @hossein as Rafal said, your for-loop is not working logical because of temp is being modified in it. I made correct your loop at the below. – Sedat Polat Oct 05 '15 at 12:24

2 Answers2

5

You could simply use

private String EliminateExtra(String str) {
    return str.replaceAll("[^a-fA-F0-9]","");
}

replaceAll uses regular expressions to find match and replace it with something else. In this case it will try to find all characters which are not in range described in negated character class [^...] and replace them with empty string (which means it removes them).

Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

In your loop for (int i = 0 ; i < temp.length() ; i++) you are modifying "temp" this causes that your loop is not working logical. I changed your for loop as;

private static String EliminateExtra(String str) {
    String temp = str.toUpperCase(); 
    String result = new String(); // create result string
    for (int i = 0 ; i < temp.length() ; i++) {
        char c = temp.charAt(i);
        if(isHexNum(c)) {
            result += String.valueOf(c); // add valid char into your result string
        }
    }
    return result ;
}
Sedat Polat
  • 1,631
  • 2
  • 18
  • 28