Вопрос

I made a method to remove some punctuation from a String but its just returning the word passed in the parameter w/ the punctuation included, can anyone spot what's wrong?

public static String removePunctuation(String word) {

    if (word.charAt(0) >= 32 && word.charAt(0) <= 46) {
        if(word.length() == 1){
            return "";
        } else {
        return removePunctuation(word.substring(1));
        }
    } else {
        if(word.length() == 1){
            return "" + word.charAt(0);
        } else {
        return word.charAt(0) + removePunctuation(word.substring(1));
        }
    }
}//end method
Это было полезно?

Решение

I ran the code you provided with the input:

h.ello and got the output hello

I am seeing a fully functional method here. I presume the punctuation you are trying to remove is not part of the ASCII range you provided in the if statement. Check your ASCII values against a chart.

ASCII values chart to compare with

Without including the proper values the input:

h[ello will return the output h[ello because the [ is ASCII value 91, which is outside the range you provided: >= 32 && <= 46

Другие советы

There is nothing wrong with your algorithm. Most likely your range (32-46) doesn't include all the punctuation you're trying to remove. For example, ? is 63, so it will not get removed.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top