nullByteMe
nullByteMe

Reputation: 6391

How can I match a char at a specific index in a string?

I have a simple string that I'm trying to determine if a specific index results in a specific char.

I'm trying to do it like this (but I get compilation errors):

if(myString.charAt(7).equals("/")) {
    // do stuff
} else {
   // do other stuff
}

Error:

Type mismatch: cannot convert from char to boolean

Upvotes: 1

Views: 128

Answers (5)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

if(myString.substring(7,8).equals("/")) 

or

if(myString.charAt(7)=='/')

or

if(myString.indexOf("/"))==7)  can be use

Upvotes: -2

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

charAt() returns char, not object, so you need to compare it that way:

if(myString.charAt(7)== '/') {
...

note the single quote around /.

Upvotes: 3

corsiKa
corsiKa

Reputation: 82559

There's a couple solutions on this answer that give you what you were probably trying to do, which is compare a single character to another single character. I won't go over that because they've done excellently.

But you can still use a String if you like, and prepare for the future. (Perhaps "/" changes to "//"?) you can do this:

if(myString.substring(7,8).equals("/")) {
    // stuff
}

Then down the road you might be like

public static final String SEPARATOR_STRING = "//";
public static final int SEPARATOR_START = 7;
public static final int SEPARATOR_END = 7 + SEPARATOR_STRING.length();

// later
if(myString.substring(SEPARATOR_START,7SEPARATOR_END).equals(SEPARATOR_STRING)) {
    // stuff
}

Upvotes: 4

kosa
kosa

Reputation: 66637

(myString.charAt(7).equals("/")

should be following because charAt() returns char:

myString.charAt(7) == '/'

Upvotes: 5

mistahenry
mistahenry

Reputation: 8724

if(myString.charAt(7)== '/') {
    // do stuff
} else {
   // do other stuff
}

Putting a character in double quotes makes it a String. Single quotes makes it a char. And you compare characters with literal == whereas you compare Objects with the equals method

Upvotes: 4

Related Questions