我正在开发一个 Anagram 程序,我正在研究一个名为diff
的方法,该方法应该返回一个包含第一个{{1}中的字符的StringBuffer但不是在第二个。因此,例如,如果StringBuffers是StringBuffer
和abba
,那么我的diff方法应该返回bb。到目前为止,我目前有一个带有if语句的循环,但它不起作用。任何帮助,将不胜感激。谢谢
acca
答案 0 :(得分:0)
我认为您正在尝试使用循环在sBuffer1
中按一个字符检查一个字符。但是String let1 = String.valueOf(sBuffer1);
会为您提供整个sBuffer1
字符串。
您需要String let1 = sBuffer1.substring(i, i + 1)
从sBuffer1
中获取一个字符来检查它是否存在于sBuffer2
中。
例如:
public static StringBuffer diff(StringBuffer sBuffer1, StringBuffer sBuffer2) {
StringBuffer diffVal = new StringBuffer();
for (int i = 0; i < sBuffer1.length(); i++) {
String let1 = sBuffer1.substring(i, i + 1); // get the character from sBuffer1
if (sBuffer2.indexOf(let1) == -1) {
diffVal.append(let1); // append the character to the diff
}
}
return diffVal;
}
答案 1 :(得分:0)
确定这可能有效,你的逻辑有点不对,这段代码很简单。如果第二个字符串缓冲区中不存在该字符,请将其添加到结果SF中。
public StringBuffer diff(){
StringBuffer diffVal = new StringBuffer();//initialize before you use it.
for (int i =0; i < sBuffer1.length(); i++){
String let1 = String.valueOf(sBuffer1.charAt(i))//get the character at the ith position.
if (sBuffer2.indexOf(let1) == -1 ){
diffVal.append(let1);
}
}
return diffVal;
}
答案 2 :(得分:0)
试试这个。
StringBuilder diffVal= new StringBuilder();
StringBuffer sBuffer1 = new StringBuffer("abbad");//input 1
StringBuffer sBuffer2 = new StringBuffer("acca");//input 2, you can ignore if you have already passed/defined these
for (int i =0; i < sBuffer1.length(); i++){
if(i >= sBuffer2.length()){//handles difference in input string length
diffVal.append(sBuffer1.substring(i, sBuffer1.length()));
break;
}
if (sBuffer1.charAt(i) != sBuffer2.charAt(i)) {
diffVal.append(sBuffer1.charAt(i));
}
}
System.out.println(diffVal);// I am printing it here
输出结果为:bbd
如果您在此处使用的字符串不需要StringBuilder
synchronized