How to compare characters in two CharSequences
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());
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");
}