我有一个家庭作业,其中我必须为 CustomString 类创建删除、反转和 filterLetters 方法。这些方法应该顾名思义,在删除方法的参数中,您提供一个字符串,其中包含您想要从实际的“myString”中删除的字母,并且该方法应该过滤您的字符数组字符串和参数,看看它是否与字符串匹配。
如果字符匹配,则该方法应该通过不将其添加到新字符串来删除它,而如果它们不匹配,则应该将字符添加到正在构建和返回的新字符串中。其他两种方法的工作原理完全相同,并且在参数中提供了字符串以反向大写或过滤字母。
我在所有方法中不断遇到同样的问题,我为字符数组创建的嵌套 for 循环遍历参数字符串的字符数组,并且对于该数组中的每个字符,它遍历当前字符串字符查看参数中的字符和当前字符串是否匹配以删除、反转或过滤。但是,这也意味着当前字符串将被运行多次,并且如果不匹配则被添加多次,因此我得到的不是我需要的字符串,而是该字符串的乘法版本。
我尝试过使用继续;运算符,但随后我得到一个缩短的版本,我需要的是,一旦添加了这些字符,即使 for 循环再次运行来检查它们,它也不会添加。但是,我不知道如何检查这一点,因为字符串中可能存在重复的字母,因此您无法交叉检查它们是否已添加到正在构建的新字符串中。
我的代码如下,我只添加了删除方法代码,因为我自始至终都遇到同样的问题,我提前感谢所有帮助!
public CustomString() {
// TODO Implement constructor
this.myString = null;
this.isSet = false;
这个 javadoc 应该解释该方法应该如何工作。
/**
* Returns a new string version of the current string where the alphabetical characters specified in the given arg, are removed.
*
* The alphabetical characters to be removed are case insensitive.
* All non-alphabetical characters are unaffected.
* If the current string is null, empty, or has not been set to a value, this method should return an empty string.
*
* Example(s):
* - For a current string "my lucky numbers are 6, 8, and 19.", calling remove("ra6") would return "my lucky numbes e 6, 8, nd 19."
* - For a current string "my lucky numbers are 6, 8, and 19.", calling remove("6,.") would return "my lucky numbers are 6, 8, and 19."
* - For a current string "my lucky numbers are 6, 8, and 19.", calling remove("") would return "my lucky numbers are 6, 8, and 19."
*
* Remember: This method builds and returns a new string, and does not directly modify the myString field.
*
* @param arg the string containing the alphabetical characters to be removed from the current string
* @return new string in which the alphabetical characters specified in the arg are removed
*/
public String remove(String arg) {
// TODO Implement method
String newString;
char[] myStrArr = myString.toCharArray();
char[] argArr = arg.toCharArray();
String newStr = ""; //a,1 and za,,231
for (int i = 0; i < argArr.length; i++) {
for (int x = 0; x < myStrArr.length; x++) {
if(Character.isLetter(argArr[i]) && Character.isLetter(myStrArr[x])) {
if ((Character.toUpperCase(argArr[i]) == myStrArr[x]) || (Character.toLowerCase(argArr[i]) == myStrArr[x])) {
continue;
} else {
String newChar = Character.toString(myStrArr[x]);
newStr += newChar;
}
} else if (Character.isDigit(argArr[i]) && Character.isDigit(myStrArr[x])) {
if(argArr[i] == myStrArr[x]) {
continue;
} else {
String newChar = Character.toString(myStrArr[x]);
newStr += newChar;
}
} else {
continue;
}
}
}
return newStr;
}
这是结果:
当前字符串:abc@,123 使用remove("a3,")后的新字符串:bc12 删除后我们应该得到什么:bc@,12
你能不能不让
myStrArr
成为外循环,然后对于带有argArr
的内循环,使用break
来停止它(而不是使用continue
),因为你已经处理完了myStrArr
信,所以可以继续下一封吗?