Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare characters in two CharSequences

How should I compare two characters of two CharSequences?

These are my two CharSequences:

CharSequence name1 = fname.getText();
CharSequence name2 = sname.getText();

If I try to compare like this:

if(name1[i] == name2[j])

..it gives me errors.

like image 858
Arush Kamboj Avatar asked Feb 04 '12 07:02

Arush Kamboj


3 Answers

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))
like image 126
Michael Konietzka Avatar answered Sep 18 '22 18:09

Michael Konietzka


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");
}
like image 38
user370305 Avatar answered Sep 16 '22 18:09

user370305


String name1 = editText1.getText().toString();
String name2 = editText2.getText().toString();

To compare particular chars 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 integers - with simple ==.

Comparing whole Strings:

// 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 Strings.

name1.equalsIgnoreCase(name2);

or:

name1.toLowerCase().contentEquals(name2.toLowerCase());
like image 41
Marcin Milejski Avatar answered Sep 17 '22 18:09

Marcin Milejski