Returns a new string version of the current string where all the letters either >= or <= the given char n, are removed.
The given letter may be a-z or A-Z, inclusive. The letters to be removed are case insensitive. If 'more' is false, all letters less than or equal to n will be removed in the returned string. If 'more' is true, all letters greater than or equal to n will be removed in the returned string. If the current string is null, the method should return an empty string. If n is not a letter (and the current string is not null), the method should return an empty string.
Questions: Since the method receives char n, how do I apply for loop to each character? Do I use arrayOfArg and is it correct to use arrayOfArg[i] to store letters more than the letter?
public String filterLetters(char n, boolean more) {
char [] arrayOfArg = n.toCharArray();
String myNewString = "";
String removedChar = "";
if (n == null) {
return "";
}
for (int i = 0; i < Character.length; i ) {
if (more == false) {
//all letters less than or equal to n will be removed in the returned string
if (Character.isLetter(i) == true) continue;
removedChar = arrayOfArg[i] ;
myNewString = arrayOfArg.replace(removedChar,"");
}
if (more == true) {
//all letters less than or equal to n will be removed in the returned string
if (Character.isLetter(i) == true) continue;
removedChar = arrayOfArg[i] -- ;
myNewString = arrayOfArg.replace(removedChar,"");
}
}
return myNewString;
}
CodePudding user response:
This is a slight modification to the code you requested but the output works properly. I'm sure someone else has a better idea than me. This is just a starting place.
public static String filterLetters(String word, String n, boolean more) {
String[] alphabet = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
int charValue = 0;
//Find Numerical Value of Char n
for (int i = 0; i < alphabet.length; i ) {
if (alphabet[i].equalsIgnoreCase(n)) {
charValue = i 1;
}
}
if (more) {
for (int i = charValue; i < alphabet.length; i ) {
word = word.replaceAll(alphabet[i],"");
}
} else {
for (int i = charValue; i > 0; i--) {
word = word.replaceAll(alphabet[i],"");
}
}
return word;
}
CodePudding user response:
Use regex!
public String filterLetters(String str, char n, boolean more) {
if (str == null || !Character.isLetter(n)) {
return "";
}
String range = more ? n "-z" : "a-" n;
return str.replaceAll("(?i)[" range "]", "");
}
This works by creating a regular expression as follows:
- if
more
is true:(?i)[n-z]
- if
more
is false:(?i)[a-n]
where "n" is the actual char passed in.
(?i)
flag turns on case insensitivity.
[a-n]
is the range (inclusive) of characters from a
to n
.
[n-z]
is the range (inclusive) of characters from n
to z
.
Note: The necessary String
parameter has been added to the method.