• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do I compare the contents of a char?

 
Kristian Andersson
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got a rather silly assignment in which I am supposed to change all the "com"'s in a String, to "borom"'s. That is, the word "complicated" is supposed to be printed out as "boromplicated". And so on.
Anyway, I'm not asking of how to do it. The problem is, how do I check and compare the contents of a StringBuffer? I am supposed (and I happen to believe that it is also the best way) to use a StringBuffer, created from the original String that I have.
The way I'm thinking of doing this is:
1. Start a loop with the same length as the StringBuffer.
2. Every time in this loop, I want to compare the contents of one place in the StringBuffer to a "c". If it is a "c" then I shall imediately begin to check if the following letters happen to be "o" and "m".
3. If they are, I replace the three letters with "borom".
The code that I have is far from finnished, since the problem occurs quite "early". Anyway, here's the little code that I have managed to create so far:

Oh, almost forgot. Well, maybe not but. In short; the problem can be stated as (forgive me for all of the quite unnessecary chit-chat bove):
"How do I compare the contents of a char?"
....Well. This is the same as the name of the subject. o_O'
 
Joe Ess
Bartender
Posts: 9312
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Variables of the primitive type char can be compared using the equality operator ==. They cannot be passed to equals(), which is defined in the class java.lang.Object as taking an Object argument.
 
Kristian Andersson
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you try to explain what passing an Object means? I'm quite lost when it comes to all theese terms. Which is why I don't dare to check the API. I did however, on this assignment.
I've tried to type something like this:
if (charAt(i) == "c")
but it doesn't work. I suppose I am supposed to get hold of the corresponding "char-number" of the letter "c". That is, say the letter "c" is the number "54" in ASCII-code, then I am supposed to check if:
charAt(i) == 54
right? That's quite clever, I should've thought of it before.
 
Joe Ess
Bartender
Posts: 9312
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Kristian Andersson:

if (charAt(i) == "c")

Two things. First, charAt() is a method of class String, so you need to invoke it on a String, like this: s.charAt(i). Second, "c" is a String that contains one character. A character literal has only single quotes, like 'c'.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic