Strings in Java

Recall that a class is a description of an object type. An object is an instantiation of a class. A class may have one or more constructors, which are called when an object is created.

An object variable is essentially a reference to the actual storage of the object. When an object variable is declared but not initialized, it will hold the null reference. When an object variable is passed as a parameter to a method, it actually passes the reference to the original object. (The reference is copied and passed into the method, but not the object itself.)

The java.lang.String class is a class for character strings. A String object is immutable; once it is created, it can not be changed.

The Java language provides special support for the string concatenation operator (+), and for conversion of other objects to strings (the toString() method).

The document on the String class can be found: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

The following are examples using the String class:

String a = “Hello World”;
String b = a;
String c = new String(“Hello World”);
String d = “Hello ” + “World”;
char[] arr = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
String e = new String(arr);

Constructors

  • public String(String original)  Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.
  • public String(char[] value)  Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.

Compare Strings

The following methods are useful for comparing two Strings.

  • public boolean equals(Object anObject)  Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
  • public boolean equalsIgnoreCase(String anotherString)  Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.
  • public int compareTo(String anotherString)  Compares two strings lexicographically. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true. This is the definition of lexicographic ordering.  If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both.

Some examples:

System.out.println(c.equals(a));
System.out.println(e.equals(a));
System.out.println(c.equalsIgnoreCase("hello world"));

System.out.println(c.compareTo(a));
System.out.println(c.compareTo("Iello World"));
System.out.println(c.compareTo("Hello Xorld"));
System.out.println(c.compareTo("Aello World"));

Generate Strings

The following methods will generate new strings based on the original string. Note that the returned strings from the following method are newly created string.

  • public String substring(int beginIndex, int endIndex)  Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex – 1. Thus the length of the substring is endIndex-beginIndex.
  • public String substring(int beginIndex)  Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
  • public String toLowerCase()
  • public String toUpperCase()  Converts all of the characters in this String to lower case / upper case.
  • public String trim()  Returns a copy of the string, with leading and trailing whitespace omitted.
  • public String concat(String str) Concatenates the specified string to the end of this string.

Some examples:

System.out.println(c.substring(1, c.length() - 1));
System.out.println(c.substring(1));
System.out.println(c.toLowerCase());
System.out.println(c.toUpperCase());
System.out.println(" Hello ".trim());

Search in Strings

  • public boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
  • public boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
  • public int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.
  • public int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
  • public int lastIndexOf(String str)  Returns the index within this string of the last occurrence of the specified substring.
  • public char charAt(int index)  Returns the char value at the specified index. An index ranges from 0 to length() – 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

Some examples:

System.out.println(c.startsWith("Hell"));
System.out.println(c.startsWith("ell"));
System.out.println(c.endsWith("orld"));
System.out.println(c.indexOf("He"));
System.out.println(c.indexOf("ll"));
System.out.println(c.charAt(0) + ", " + c.charAt(1));

Overloading

If two methods of a class have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded. For example, the following two methods have the same name but different parameters.

public String substring(int beginIndex, int endIndex)
public String substring(int beginIndex)

When we call such a method by passing in parameters, the system will decide which method to be run based on both the method name and the parameters.

Example

The following piece of code is a simple example of extracting substrings. Image we have the content of a web page (HTML file) in a string; each HTML has a title which is encapsulated with the tagsand. The code searches for the ending of the opening tagand the beginning of the close tagand extract the substring in the middle.

String str = "...Title A...";
String tagOpen = ""; String tagClose = "";
int begin = str.indexOf(tagOpen) + tagOpen.length();
int end = str.indexOf(tagClose, begin);
String substr = str.substring(begin, end);
System.out.println(substr);

Comments

comments

Tagged with: ,
Posted in Java