Is there a method in the string class that returns the number of characters in the string?

Although concatenation is the only operator that can be applied to String objects, Java has many methods in the String class that allow us to manipulate text quite easily. In Chapter 3, we examined the methods equals and compareTo that can be used for comparing and ordering strings. In this section, we extend our study of string methods with an examination of many of the more commonly used ones. Our study will not be complete; if you are going to be doing a lot of work with strings, it would probably be a good idea to take a close look at the full set of methods available in the class.

length

In some ways, strings in Java are much like arrays. For example, both arrays and strings have lengths associated with them. The concepts are not, however, identical. For an array, its length is a property; the array a has a length given by a.length. On the other hand, the length of a string is given by the instance method Length in the String class that returns the number of characters in its implicit object; the string s has a length given by the value of s.length().

Example 1

If we had made the declaration
   String s = "Sergiy";
then the statement
   System.out.println(s.length());
would print the value 6.

charAt

Another concept seen with both arrays and strings is that of an index. Recall that, for an array, an index gave the position of an element in the array, starting from zero. With strings, an index gives the position of a character in the string, again starting from zero. There are a number of methods in the String class that use an index. The simplest is charAt, an instance method whose header has the form

public char charAt (int i)

The method returns the value of the character at index i in its implicit String object. A value of i out of the range of the string will cause a StringIndexOutOfBoundsException to be thrown.2

Example 2

Suppose that we have made the declaration
   String s = "Jasper";
Then

  1. s.charAt(0) will return 'J'
  2. s.charAt(5) will return 'r'
  3. s.charAt(6) will throw a StringIndexOutOfBoundsException

indexOf

The method indexOf enables us to locate a particular character in a string. The method is overloaded with the simplest version having the following header:

public int indexOf (char c)

This method searches its implicit String object from left to right for an occurrence of c. If c is a character in the string, the method returns the index of the leftmost occurrence of c; if c does not occur in the string, the method returns -1. The type of argument passes to indexOf is normally char but the method permits the use of an arguments of any integer type other than long.

Another version of indexOf is useful if we do not necessarily want the leftmost occurrence of a character. This version has the header

public int indexOf (char c, int i)

This form of the method returns the index of the first occurrence of c that has index at least equal to i. As before, it returns -1 if no such occurrence exists.

Example 3

Given the declaration
   String s = "Toronto";
Then
a) s.indexOf('T') will return 0
b) s.indexOf('t') will return 5
c) s.indexOf('m') will return -1
d) s.indexOf('o',3) will return 3
e) s.indexOf('o',4) will return 6
f) s.indexOf('r',3) will return -1

To illustrate how these methods can be used, the next example shoes two ways that we could perform a simple task involving strings.

Example4

Both versions of method printLocations print the indices in the string s of the locations that contain the character c. The first method uses charAt to examine every character while the second method uses indexOf to jump to the locations in which the character occurs. In the second method, the constant NOT_FOUND is set to -1, the value returned be indexOf if it fails to find the specific character.

public static void printLocations (char c, String s) { for (int i = 0; i < s.length(); i++) if (s.charAt(i) == c) System.out.println(i); } public static void printLocations (char c, String s) { final int NOT_FOUND = -1; int next = s.indexOf(c); while (next != NOT_FOUND) { System.out.println(next); next = s.indexOf(c,next+1); } }

substring

Just as we can use charAt to extract characters from a string, we can use substring to extract a part of a string from a string. The substring method, like indexOf, is overloaded. Its simplest form has the header

public String substring (int start)

this method returns a String object, the substring of its implicit object starting at the index specified by start and continuing the end of the string. If the value of start is less than zero or greater than the length of the string, the method throws a StringIndexOutOfBoundsException. This method also exists in a two-parameter form with the header

public String substring (int start, int pastEnd)

this form returns a substring of its implicit object from the index specified by start to the character before the index specified by pastEnd. Although this may appear at first to be a bit strange, it turns out to be a useful and convenient form. For one thing, in this form the length of the substring is specifies simply by the difference between the two parameters.

Example 5

Given the declaration
   String s = "Brian Auyeung";
then

a) s.substring(3) will return "an Auyeung"

b) s.substring(2,5) will return "ian"

c) s.substring(20) will throw a StringIndexOutOfBoundsException

trim

Another method that is useful in manipulating strings containing text is trim, an instance method in the String class that returns a string that is identical to its implicit object but with any leasing or trailing blanks removed. It also removes any leasing or trailing white space characters. White space includes blanks and control characters such as tab (\t), newline (\n), carriage return (\r), and form feed (\f) characters. The method does not alter the original, immutable string. Instead, it creates a copy with the appropriate alterations.

Example 6

Given that
s = " Lots of extra blanks ";
then
   s.trim()
will return the string
   "Lots of extra blanks"
with no leading or trailing white spaces. Notice that the method does not alter interior blanks; the extra blanks between words in s are still in the string returned by the method.

To show these methods in context, let us construct a method that removes all excess blanks in a string.

Example 7

The following method will create a string identical to its string parameter but with all leading blanks, trailing blanks and instances of two or more consecutive blanks removed. The method first uses trim to eliminate any leading or trailing white space it then uses indexOf to locate remaining blanks. For each blank found by indexOf, charAt is used to see if the adjacent character is also a blank and, if it is, substring is used to eliminate the second blank. Once all excess blanks have been removed, the method returns the compressed string.

public static String removeSpaces (String oldString) { final int NOT_FOUND = -1; String newString = oldString.trim(); int nextBalnk = newString.indexOf(' '); while (nextBlank != NOT_FOUND) { while (newString.charAt(nextBlank+1) == ' ') newString = newString.substring(0,nextBlank+1) + newString.substring(nextBlank+2); nextBlank = newString.iindexOf(' ',nextBlank+1); } return newString; }

To use this method to eliminate excess blanks in myString, we could write

myString = removeSpaces(myString);

toUpperCase toLowerCase equalsIgnoreCase

Recall that, in comparing strings, upper case letters and lower case letters are considered to be different. If we want to compare strings containing letters, we can avoid problems involving the case of letters in a number of ways. One possibility is to create a string that is equal to a given string but with all letters converted to upper case (and all other characters left unchanged) by using the method toUpperCase() from the String class. The method has header

public String toUpperCase()

As you might expect, there is also a method called toLowerCase in the String class whose form and behaviour are exactly analogous to that of toUpperCase. As usual, since strings are immutable, neither of these methods alters its implicit string object. Instead, they return new string objects that may contain new characters. One other solution to the problems produced by different cases is to do comparisons with the method equalsIgnoreCase which has header

boolean equalsIgnoreCase (String other)

Its effect is exactly the same as that of equals but, as the name suggests, upper and lower case characters will be considered equal.

Example 8

Given the declaration
   String s = "Bart & Lisa";
then
a) s.toLowerCase() will return "bart & lisa"

b) s.toUpperCase() will return "BART & LISA"

c) s.equalsIgnoreCase("BART & lisa") will return true

valueOf

Values of any type can be converted to strings. To convert an object to a string, we can use the object�s toString method. To convert a value in any of Java�s primitive type to a string, we can use the class method valueOf in the String class. The method is overloaded so that its parameter can be of any primitive type.

Example 9

a) String.valueOf(123) returns "123"
b) String.valueOf('a') returns "a"
c) String.valueOf(2.5) returns "2.5"

Java allows us to chain instance method in order to produce compound effects. This can be very effective in operations involving strings. Given an expression of the form

..

Java will first execute using as its implicit object parameter. It will then execute using the value returned by the first call as its implicit object.

Example 10

If s has the value "abc", then the expression s.toUpperCase().charAt(1) will be evaluated as follows:
   s.toUpperCase() returns the value "ABC".
   "ABC".charAt(1) then returns the value 'B'.
Note that the operations do not change the value of the string s.

Exercise 9.2

  1. Given the declaration String s = "Amanda Chui"; Find the value of each expression. a) s.charAt(3) b) s.substring(8) c) s.length() d) s.indexOf('a') e) s.charAt(0) f) s.substring(1,4) g) s.substring(1) h) s.indexOf('m',4) i) s.charAt(4) j) s.substring(4,5)
  2. State the value of each expression. a) String.valueOf(2*4) b) String.valueOf(27%7) c) String.valueOf((char)('A'+ 4)) d) String.valueOf(3 < 4 && 5 < 6)
  3. Assuming that the string name has the value "Avi Laurie" , find the value of each expression. a) name.toLowerCase().indexOf('a') b) name.toUpperCase().charAt(5) c) name.substring(3).indexOf('i') d) name.substring(2).toUpperCase() e) name.toUpperCase().indexOf('A',1) f) name.substring(name.indexOf(' ')+1).length()
  4. Complete the definition of the method count so that it returns the number of occurrences of the character c in the string s. public static int count (char c, String s)
  5. Complete the definition of the method replace so that it returns a string in which all occurrences of oldChar in the string s are replaced by newChar. public static String replace(String s, char oldChar, char newChar)
  6. Write a method called averageLength that has one String parameter, s. The method should return, as a double value, the average length of the words in s. Assume that s consists only of words separated by single blanks, without any leading or trailing blanks.
  7. A hetero-literal word pair is defined as a pair of words having no letters in common. As examples, "TERRY" and "FOX" from a hetero-literal word pair "WAYNE" and "GRETZKY" do not (because of the 'E' and 'Y' in each word). Write a method called isHeteroPair that has two String parameters, wordA and wordB. The mehod should return a boolean value: true if wordA and wordB form a hetero-literal word pair and false if they do not. You may assume that all characters are uppercase letters.

In which string class function returns the number of characters in a string?

String Length One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

Which method yields the number of characters in a string?

Java String length() method is used to find out the length of a String. This method counts the number of characters in a String including the white spaces and returns the count.

What is the method in class string to returns the length of a string?

The length() method returns the length of a specified string.

How do you find the number of characters in a string in Java?

Java has an inbuilt method called length() to find the number of characters of any String. int length(); where length() is a method to find the number of characters and returns the result as an integer.