Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compare a String with a Char

Guys how do i compare a String with a char?

heres my code :

private String s;
private char c;

public K(String string, char cc){
    setS(string);
    setC(cc);
}

public void setS(String string){
    this.s = string;
}

public void setC(char cc){
    this.c = cc;
}

public boolean equals(K other){
    return s.equals(c);
}

public boolean try(){
    return s.equals(c);
}

if i call my method try, it always returns me false even if i set both s = "s" and c = 's'.

like image 852
user8120322 Avatar asked Jun 18 '17 14:06

user8120322


People also ask

Can you use == with char?

Yes, char is just like any other primitive type, you can just compare them by == .

How do you compare strings to characters?

strcmp is used to compare two different C strings. When the strings passed to strcmp contains exactly same characters in every index and have exactly same length, it returns 0. For example, i will be 0 in the following code: char str1[] = "Look Here"; char str2[] = "Look Here"; int i = strcmp(str1, str2);

Can you compare string with char in C?

C strcmp()The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

Do you use == or .equals for char?

Because char is a primitive type and does not implement equals , == compares char values directly in this case, where as String is an object. So for object comparison, the equality operator is applied to the references to the objects, not the objects they point to.


1 Answers

The first thing I would say to any of my junior devs is to not use the word "try" as a method name, because try is a reserved keyword in java.

Secondly think that there are a few things which you need to consider in your method.

If you compare things of two different types they will never be the same. A String can be null. How long the string is. The first char.

I would write the method like :

public boolean isSame() {
    if (s != null && s.length() == 1 { 
        return s.charAt(0) == c;
    }
    return false;
}
like image 164
MartinByers Avatar answered Nov 06 '22 18:11

MartinByers