0

I want to check if the char at a certain index in a StringBuffer is equal to a char. I am getting an error, how do I compare them? Here's my code:

//I have an established StringBuffer called stringbuffer

char[] mychar = null;
for(int i = 0; i < stringbuffer.length(); ++i){
        if(stringbuffer.charAt(i) != " "){
              mychar[i] = stringbuffer.charAt(i);
        }
}

The error I am getting is incompatible operand types char and String. Not sure why, because I am comparing a char of a StringBuffer, not a String or StringBuffer.

1
  • You're comparing a char with a String literal. Commented Feb 19, 2015 at 20:24

1 Answer 1

1

Values of char type are surrounded with ', Strings are surrounded with " and you can't compare char with String with == in Java.

Try with

if(stringbuffer.charAt(i) != ' '){

or maybe cleaner (but this will check fore more than just simple ' ')

if (! Character.isWhitespace(stringbuffer.charAt(i)) ) {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.