0

I am receiving a character array where it has valid and invalid characters. I need to only retrieve the characters that are valid. How can I do this ?

char[]ch = str.toCharacterArray();
for(int i=0;i<ch.length.i++){
    if(!Character.isLetter(ch[i]))
         system.out.println("not valid");
    else  
        system.out.println("valid");
}

I don't think the above code works because I get invalid for all the valid and invalid characters in the character array.

by meaning characters I am expecting all alphanumeric and special characters

Note: I am getting values from the server, therefore the character array contains valid and invalid characters.

7
  • You start off by talking about a byte array but then you talk about characters, and your code has a string. Which is it? And what sort of "invalid characters" do you mean? Commented Jan 30, 2013 at 8:17
  • 1
    I don't see a good reason why the server should be giving you invalid characters unless you are getting binary data which happens to contain some text and you don't know what to do with the rest of the content. There are is only two characters defined as invalid but I suspect you want printable characters. Commented Jan 30, 2013 at 8:18
  • I have edited the post, Yes i want to have printable characters. Commented Jan 30, 2013 at 8:19
  • If the server is not broken, then it's sending you "correct" data in some format. I can't imagine a case where plucking the printable characters out of the data is preferably to truly understanding the format and extracting what you know must be the data you care about. Commented Jan 30, 2013 at 8:27
  • So you just want letter/numbers, and remove all spaces and other symbols or control chars? Commented Jan 30, 2013 at 8:32

2 Answers 2

1

try following method:

// assume input is not too large string
public static String extractPrintableChars(final String input) {
    String out = input;
    if(input != null) {
        char[] charArr = input.toCharArray();
        StringBuilder sb = new StringBuilder();  
        for (char ch : charArr) {
            if(Character.isDefined(ch) && !Character.isISOControl(ch)) {
                sb.append(ch);
            }
        }
        out = sb.toString();
    }
    return out;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Have a look into Matcher class available in java. I don't think it to be wise to loop over all the characters until there is a max Cap for it.

/[^0-9]+/g, '' 

with above regEx it will wipe out all the charecters other then numeric with noting. Modify it as per your need.

regards Punith

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.