Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check length of a String in Android

Tags:

string

android

I want to check whether the entered strings length is between 3 to 8 characters. Previously I used if condition and it worked. However when I introduced some substring from the string , one of the if statements doesnt work. Can some one help me to understand why. Thanks.

My codes is

Working Code:

   text = et.getText().toString();
    l = text.length();
    a = text.substring(0, 1);
    if (l >=9) tv.setText("Invalid length!!! Please check your code");
    if (l <= 2) tv.setText("Invalid length! Please check your code");

And here, the second if statement doesnt work.

text = et.getText().toString();
l = text.length();
a = text.substring(0, 1);
c = text.substring(1, 2);
d = text.substring(3, 4);
e = text.substring(4);
if (l >=9) tv.setText("Invalid length!!! Please check your code");
if (l <= 2) tv.setText("Invalid length! Please check your code");
like image 480
AUJ Avatar asked Feb 10 '14 03:02

AUJ


People also ask

What is length () in Java?

The length() method returns the length of a specified string. Note: The length of an empty string is 0.

Which function is used to find the string length?

As you know, the best way to find the length of a string is by using the strlen() function.

How do I get the length of a string in Java?

To calculate the length of a string in Java, you can use an inbuilt length() method of the Java string class. In Java, strings are objects created using the string class and the length() method is a public member method of this class. So, any variable of type string can access this method using the . (dot) operator.


1 Answers

You will want to ensure that you handle a null string as well as ensuring your string is within the limits you want. consider:

text = et.getText().toString();
if (text == null || text.length() < 3 || text.length > 8) {
    tv.setText("Invalid length, should be from 3 to 8 characters. Please check your code");
} else {
    a = text.substring(0,1);
    b = text.substring(1,2);

    c = text.substring(3,4);
    if (text.length() > 3) {
      d = text.substring(4);
    } else {
         d = null;
    }
}
like image 80
ErstwhileIII Avatar answered Nov 15 '22 23:11

ErstwhileIII