How should I compare two characters of two CharSequence
s?
These are my two CharSequence
s:
CharSequence name1 = fname.getText();
CharSequence name2 = sname.getText();
If I try to compare like this:
if(name1[i] == name2[j])
..it gives me errors.
Use CharSequence.html#charAt(int) to get the char
at a specified position.
You can then compare char
with ==
Regarding your code in the question, this will result in
if(name1.charAt(i) == name2.charAt(j))
If possible compare two Strings
,
Instead of ChracterSequence
comparison something like,
String name1 = edtTextName1.getText().toString().trim();
String name2 = edtTextName2.getText().toString().trim();
if(name1.equals(name2))
{
Log.i("Result","True");
}
else
{
Log.i("Result","false");
}
String name1 = editText1.getText().toString();
String name2 = editText2.getText().toString();
To compare particular char
s in your String, you can use char charAt(int)
method also from String
type. Here is example use:
if(name1.charAt(2) == name2.charAt(0)){
// Do your stuff
}
You have to remember that char charAt(int)
is zero-based so 0 is first, 1 is second and so on.
And in this example you can see that I compared two chars just like I would compare int
egers - with simple ==
.
Comparing whole String
s:
// This returns true if Strings are equal:
name1.contentEquals(name2);
// This returns 0 if Strings are equal:
name1.compareTo(name2);
To make it case insensitive you can use method from String
type toLowerCase()
on both String
s.
name1.equalsIgnoreCase(name2);
or:
name1.toLowerCase().contentEquals(name2.toLowerCase());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With