Pages

Saturday, June 09, 2012

Java String Methods - Length

w7r.blogspot.com

The "string".length() Method

Length is a method/function used to obtain how many characters are present. These characters include spaces, punctuation, underscores, symbols in unicode, numbers and just about anything else you can think of.

For example, "iRobot" is a string that contains 6 characters, 'i', 'R', 'o', 'b', 'o', and 't'. Each character has its own index (location) in the String, in which calling "iRobot".length() will specify how many characters or spaces there are in the String.

This knowledge would be useless without an application so imagine you, a software developer, needs to ensure your clients names will fit on the screen of your newly built program. Without going through your clients one by one, you could use the length function on each one of their names in your database to find the longest name you must display. Code for this will be in example #1.

Example #1

public static void main(String[] args) {
 String[] clientNames = new String[]{
  "Jacobs", "Trout", "Semor", "Lee","Poppins",
  "Jenson", "Johnson","Peterson", "Kim", "Brown"};

 int longest = 0;

 for(String s: clientNames) {
  if(s.length()>longest) {
   longest=s.length();
  }
 }

 System.out.println("Minimum characters for display: "+longest);
}


In example #1 the length method is used to figure out which string has the most characters. It is important to realize that Strings do not have a character at someString[someString.length()] would throw an exception and terminate your program. Remember that arrays and Strings alike are indexed starting with 0.

The last character of a String can be obtained by someString[someString.length()-1].

More On Java Strings

No comments:

Post a Comment