-4

I am creating an anagram program which compares two strings and am unsure how to go about creating a boolean that returns true if a character appears in both words.

My code is as follows:

StringBuffer strbuff1 = new StringBuffer(""); 

private StringBuffer strbuff2 = new StringBuffer(""); 

public Anagram (String s1, String s2) {

    s1 = strbuff1.toString();
    s2 = strbuff2.toString();

     } 

public boolean contains(char chart1) {
        return true;        //what do I put here? 
    }

}
ZygD
  • 22,092
  • 39
  • 79
  • 102
CsStudent
  • 1
  • 2
  • 1
    Possible duplicate of [In Java, how do I check if a string contains a substring (ignoring case)?](http://stackoverflow.com/questions/2275004/in-java-how-do-i-check-if-a-string-contains-a-substring-ignoring-case) – dguay Nov 18 '15 at 19:23
  • Did you do any research? Have you made an attempt? – brso05 Nov 18 '15 at 19:24
  • Please don't use StringBuffer as it was replaced by StringBuilder more than ten years ago. – Peter Lawrey Nov 22 '15 at 20:13

2 Answers2

1

So you should be able to use the StringBuffer method indexOf. Please check out the api documentation here: http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html#indexOf(java.lang.String)

Something like:

public boolean contains(char chart1) {
    if(strbuff1.indexOf(chart1) >= 0 && strbuff2.indexOf(chart1) >= 0) {
       return true;  
    }
    return false;      
}

However, I also think that your constructor's variable assignments may be backwards.

You probably want strbuff1 = new StringBuffer(s1);

This will create a new StringBuffer with the contents of the given String object.

Good luck!

*Edited to include a check for both words.

Kyle Gowen
  • 467
  • 2
  • 8
0

This should give you what you need

public boolean contains(char chart1) {
    return stringOne.contains(Character.toString(chart1)) &&
        stringTwo.contains(Character.toString(chart1));
}

This will return true if the provided character is contained within both strings, false otherwise

Brandon Laidig
  • 430
  • 2
  • 14