mlhmz
mlhmz

Reputation: 47

Exclude Special Characters from String Java

I am pretty new to Java and i am writing a little Encrypt, Decrypt Tool for School and i wanted to ask how i can exclude Special Characters from it, i already tried methods like "contains" but i doesn't really work. my code looks like this:


public void bEncode_ActionPerformed(ActionEvent evt) {
    String Input = jTextField1.getText();
    String Output = "";
    String Specialcharacters = "!§$%&/()=?.,-_+*:;";
    jTextField2.setText("Encoding...");
    char c;
    int Number = (Integer) jSpinner1Model.getNumber();
    int asc;
    for (int i = 0; i < Input.length(); i++) {
      if(!Input.contains(Specialcharacters){  
      c = Input.charAt(i);
      asc = (int) c;
      asc = asc + Number;
      if (asc>90) asc = asc-26;
      Output = Output + (char) asc;
      } else {

      }  
    }
    jTextField2.setText(Output);

  }

Is there any Method to get this working?

Upvotes: 0

Views: 1313

Answers (1)

tinymothbrain
tinymothbrain

Reputation: 412

Use a regular expression. For example, the following line will grab only letters and numbers from the given string.

String onlyLettersAndNumbers = s.replaceAll("[^0-9A-Za-z]", "");

Upvotes: 5

Related Questions