Thursday 16 March 2017

Searching Strings, Modifying a String, Data Conversion Using valueOf( ) & Changing the Case of Characters Within a String - Java Tutorials

Searching Strings

The String class provides two methods that allow you to search a string for a specified character or substring:

  • indexOf( ) Searches for the first occurrence of a character or substring.
  • lastIndexOf( ) Searches for the last occurrence of a character or substring.

These two methods are overloaded in several different ways. In all cases, the methods return the index at which the character or substring was found, or –1 on failure. 

To search for the first occurrence of a character, use

      int indexOf(int ch)

To search for the last occurrence of a character, use

      int lastIndexOf(int ch)

Here, ch is the character being sought. To search for the first or last occurrence of a substring, use

      int indexOf(String str)
      int lastIndexOf(String str)

Here, str specifies the substring. You can specify a starting point for the search using these forms:

      int indexOf(int ch, int startIndex)
      int lastIndexOf(int ch, int startIndex)

      int indexOf(String str, int startIndex)
      int lastIndexOf(String str, int startIndex)

Here, startIndex specifies the index at which point the search begins. For indexOf( ), the search runs from startIndex to the end of the string. For lastIndexOf( ), the search runs from startIndex to zero.

The following example shows how to use the various index methods to search inside of Strings:

  // Demonstrate indexOf() and lastIndexOf().
  class indexOfDemo {
    public static void main(String args[]) {
      String s = "Now is the time for all good men " +
                 "to come to the aid of their country.";

      System.out.println(s);
      System.out.println("indexOf(t) = " +
                         s.indexOf('t'));
      System.out.println("lastIndexOf(t) = " +
                         s.lastIndexOf('t'));
      System.out.println("indexOf(the) = " +
                         s.indexOf("the"));
      System.out.println("lastIndexOf(the) = " +
                         s.lastIndexOf("the"));
      System.out.println("indexOf(t, 10) = " +
                         s.indexOf('t', 10));
      System.out.println("lastIndexOf(t, 60) = " +
                         s.lastIndexOf('t', 60));
      System.out.println("indexOf(the, 10) = " +
                         s.indexOf("the", 10));
      System.out.println("lastIndexOf(the, 60) = " +
                         s.lastIndexOf("the", 60));
    }
  }

Here is the output of this program:

  Now is the time for all good men to come to the aid of 
                                           their country.
  indexOf(t) = 7
  lastIndexOf(t) = 65
  indexOf(the) = 7
  lastIndexOf(the) = 55
  indexOf(t, 10) = 11
  lastIndexOf(t, 60) = 55
  indexOf(the, 10) = 44
  lastIndexOf(the, 60) = 55




Modifying a String

Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or use one of the following String methods, which will construct a new copy of the string with your modifications complete.


substring( )

You can extract a substring using substring( ). It has two forms. The first is

      String substring(int startIndex)

Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string. The second form of substring( ) allows you to specify both the beginning and ending index of the substring:

      String substring(int startIndex, int endIndex)

Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index. The following program uses substring( ) to replace all instances of one substring with another within a string:

  // Substring replacement.
  class StringReplace {
    public static void main(String args[]) {
      String org = "This is a test. This is, too.";
      String search = "is";
      String sub = "was";
      String result = "";
      int i;

      do { // replace all matching substrings
        System.out.println(org);
        i = org.indexOf(search);
        if(i != -1) {
          result = org.substring(0, i);
          result = result + sub;
          result = result + org.substring(i + search.length());
          org = result;
        }
      } while(i != -1);

    }
  }

The output from this program is shown here:

  This is a test. This is, too.
  Thwas is a test. This is, too.
  Thwas was a test. This is, too.
  Thwas was a test. Thwas is, too.
  Thwas was a test. Thwas was, too.


concat( )

You can concatenate two strings using concat( ), shown here:

      String concat(String str)

This method creates a new object that contains the invoking string with the contents of str appended to the end. concat( ) performs the same function as +. For example,

  String s1 = "one";
  String s2 = s1.concat("two");

puts the string “onetwo” into s2. It generates the same result as the following sequence:

  String s1 = "one";
  String s2 = s1 + "two";


replace( )

The replace( ) method replaces all occurrences of one character in the invoking string with another character. It has the following general form:

      String replace(char original, char replacement)

Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example,

  String s = "Hello".replace('l', 'w');

puts the string “Hewwo” into s.


trim( )

The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. It has this general form:

      String trim( )

Here is an example:

  String s = " Hello World ".trim();

This puts the string “Hello World” into s.

The trim( ) method is quite useful when you process user commands. For example, the following program prompts the user for the name of a state and then displays that state’s capital. It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user.

  // Using trim() to process commands.
  import java.io.*;

  class UseTrim {
    public static void main(String args[])
      throws IOException
    {
      // create a BufferedReader using System.in
      BufferedReader br = new
        BufferedReader(new InputStreamReader(System.in));
      String str;

      System.out.println("Enter 'stop' to quit.");
      System.out.println("Enter State: ");
      do {
        str = br.readLine();
        str = str.trim(); // remove whitespace

        if(str.equals("Illinois"))
          System.out.println("Capital is Springfield.");
        else if(str.equals("Missouri"))
          System.out.println("Capital is Jefferson City.");
        else if(str.equals("California"))
          System.out.println("Capital is Sacramento.");
        else if(str.equals("Washington"))
          System.out.println("Capital is Olympia.");
        // ...
      } while(!str.equals("stop"));
    }
  }





Data Conversion Using valueOf( )

The valueOf( ) method converts data from its internal format into a human-readable form. It is a static method that is overloaded within String for all of Java’s built-in types, so that each type can be converted properly into a string. valueOf( ) is also overloaded for type Object, so an object of any class type you create can also be used as an argument. (Recall that Object is a superclass for all classes.) Here are a few of its forms:

      static String valueOf(double num)
      static String valueOf(long num)
      static String valueOf(Object ob)
      static String valueOf(char chars[ ])

As we discussed earlier, valueOf( ) is called when a string representation of some other type of data is needed—for example, during concatenation operations. You can call this method directly with any data type and get a reasonable String representation. All of the simple types are converted to their common String representation. Any object that you pass to valueOf( ) will return the result of a call to the object’s toString( ) method. In fact, you could just call toString( ) directly and get the same result.

For most arrays, valueOf( ) returns a rather cryptic string, which indicates that it is an array of some type. For arrays of char, however, a String object is created that contains the characters in the char array. There is a special version of valueOf( ) that allows you to specify a subset of a char array. It has this general form:

      static String valueOf(char chars[ ], int startIndex, int numChars)

Here, chars is the array that holds the characters, startIndex is the index into the array of characters at which the desired substring begins, and numChars specifies the length of the substring.




Changing the Case of Characters Within a String

The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. The toUpperCase( ) method converts all the characters in a string from lowercase to uppercase. Nonalphabetical characters, such as digits, are unaffected. Here are the general forms of these methods:

      String toLowerCase( )
      String toUpperCase( )

Both methods return a String object that contains the uppercase or lowercase equivalent of the invoking String. Here is an example that uses toLowerCase( ) and toUpperCase( ):

  // Demonstrate toUpperCase() and toLowerCase().

  class ChangeCase {
    public static void main(String args[])
    {
      String s = "This is a test.";

      System.out.println("Original: " + s);

      String upper = s.toUpperCase();
      String lower = s.toLowerCase();

      System.out.println("Uppercase: " + upper);
      System.out.println("Lowercase: " + lower);
    }
  }

The output produced by the program is shown here:

  Original: This is a test.
  Uppercase: THIS IS A TEST.
  Lowercase: this is a test.

No comments:

Post a Comment