Strings
By
Dr. G Prabhakar Raju
Asst. Professor, AU
Introduction
• A string is a sequence of characters.
• In many languages, strings are treated as an array of characters, but in
Java a string is an object.
• Every string we create is actually an object of type String.
• String constants are actually String objects.
• Example:
[Link]("This is a String, too");
• Objects of type String are immutable i.e. once a String object is created,
its contents cannot be altered.
Introduction
• In java, four predefined classes are provided that either
represent strings or provide functionality to manipulate them.
Those classes are:
– String
– StringBuffer
– StringBuilder
– StringTokenizer
String, StringBuffer, and StringBuilder classes are
defined in [Link] package and all are final.
All three implement the CharSequence interface.
Why String Handling?
String handling is required to perform following operations on
some string:
• compare two strings
• search for a substring
• concatenate two strings
• change the case of letters within a string
Creating String objects
class StringDemo
{
public static void main(String args[])
{
String strOb1 = “Students";
String strOb2 = “AU";
String strOb3 = strOb1 + " and " + strOb2;
[Link](strOb1);
[Link](strOb2);
[Link](strOb3);
}
}
String Class
String Constructor:
public String ()
public String (String strObj)
public String (char chars[])
public String (byte asciiChars [])
public String (char chars[ ], int startIndex, int numChars)
public String (byte asciiChars[ ], int startIndex, int
numChars)
Examples
char [] a = {'c', 'o', 'n', 'g', 'r', 'a', 't', 's'};
byte [] b = {65, 66, 67, 68, 69, 70, 71, 72};
String s1 = new String (a); [Link](s1);
String s2 = new String (a, 1,5);
[Link](s2);
String s3 = new String (s1); [Link](s3);
String s4 = new String (b); [Link](s4);
String s5 = new String (b, 4, 4);
[Link](s5);
congrats
ongra
congrats
ABCDEFGH
EFGH
String Concatenation
• Concatenating Strings:
String age = "9";
String s = "He is " + age + " years old.";
[Link](s);
• Using concatenation to prevent long lines:
String longStr = “This could have been” +
“a very long line that would have” +
“wrapped around. But string”+
“concatenation prevents this.”;
[Link](longStr);
String Concatenation with Other Data Types
• We can concatenate strings with other types of data.
Example:
int age = 9;
String s = "He is " + age + " years old.";
[Link](s);
Methods of String class
• String Length:
length() returns the length of the string i.e. number of
characters.
int length()
Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
[Link]([Link]());
Character Extraction
• charAt(): used to obtain the character from the specified index
from a string.
public char charAt (int index);
Example:
char ch;
ch = "abc".charAt(1);
Methods Cont…
• getChars(): used to obtain set of characters from the string.
void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart)
Example: String s = “KAMAL”;
char b[] = new char [10];
b[0] = ‘N’; b[1] = ‘E’;
b[2] = ‘E’; b[3] = ‘L’;
[Link](0, 4, b, 4);
[Link](b);
Output: NEELKAMA
Methods Cont…
• toCharArray(): returns a character array initialized by the
contents of the string.
char [] to Char Array();
Example: String s = “INDIA”;
char c[] = [Link]();
for (int i=0; i<[Link]; i++)
{
if (c[i]>= 65 && c[i]<=90)
c[i] += 32;
[Link](c);
}
String Comparison
• equals(): used to compare two strings for equality.
Comparison is case-sensitive.
public boolean equals (Object str)
• equalsIgnoreCase( ): To perform a comparison that ignores case
differences.
Note:
• This method is defined in Object class and overridden in String class.
• equals(), in Object class, compares the value of reference not the content.
• In String class, equals method is overridden for content-wise comparison of two
strings.
Example
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
[Link](s1 + " equals " + s2 + " -> " +
[Link](s2));
[Link](s1 + " equals " + s3 + " -> " +
[Link](s3));
[Link](s1 + " equals " + s4 + " -> " +
[Link](s4));
[Link](s1 + " equalsIgnoreCase " + s4 + " -> “
+[Link](s4));
}
}
String Comparison
• startsWith( ) and endsWith( ):
– The startsWith( ) method determines whether a given String
begins with a specified string.
– Conversely, endsWith( ) determines whether the String in
question ends with a specified string.
boolean startsWith(String str)
boolean endsWith(String str)
String Comparison
compareTo( ):
• A string is less than another if it comes before the other in
dictionary order.
• A string is greater than another if it comes after the other in
dictionary order.
int compareTo(String str)
Example
class SortString {
static String arr[] = {"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country"};
public static void main(String args[]) {
for(int j = 0; j < [Link]; j++) {
for(int i = j + 1; i < [Link]; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
[Link](arr[j]);
}
}
}
Searching Strings
• The String class provides two methods that allow us to search a string for a
specified character or substring:
indexOf( ): Searches for the first occurrence of a character or substring.
int indexOf(int ch)
lastIndexOf( ): Searches for the last occurrence of a character or
substring.
int lastIndexOf(int ch)
• To search for the first or last occurrence of a substring, use
int indexOf(String str)
int lastIndexOf(String str)
• We 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.
Example
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.";
[Link](s);
[Link]("indexOf(t) = " + [Link]('t'));
[Link]("lastIndexOf(t) = " + [Link]('t'));
[Link]("indexOf(the) = " + [Link]("the"));
[Link]("lastIndexOf(the) = " + [Link]("the"));
[Link]("indexOf(t, 10) = " + [Link]('t', 10));
[Link]("lastIndexOf(t, 60) = " + [Link]('t', 60));
[Link]("indexOf(the, 10) = " + [Link]("the", 10));
[Link]("lastIndexOf(the, 60) = " + [Link]("the", 60));
}
}
Modifying a String
• Because String objects are immutable, whenever we want to modify a
String, we must either copy it into a StringBuffer or StringBuilder, or use
one of the following String methods, which will construct a new copy of
the string with modifications.
• substring(): used to extract a part of a string.
public String substring (int start_index)
public String substring (int start_index, int end_index)
Example: String s = “ABCDEFG”;
String t = [Link](2); [Link] (t);
String u = [Link] (1, 4); [Link] (u);
CDEFG
BCD
concat( ): used to concatenate two strings.
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 +.
Example:
String s1 = "one"; String s2 = [Link]("two");
• It generates the same result as the following sequence:
String s1 = "one"; String s2 = s1 + "two";
replace( ): The replace( ) method has two forms.
• The first 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.
Example: String s = "Hello".replace('l', 'w');
• The second form of replace( ) replaces one character sequence with another.
It has this general form:
String replace(CharSequence original, CharSequence replacement)
trim( )
• The trim( ) method returns a copy of the invoking string from which
any leading and trailing whitespace has been removed.
String trim( )
Example:
String s = " Hello World ".trim();
This puts the string “Hello World” into s.
Changing the Case of Characters Within a String
toLowerCase() & toUpperCase()
• Both methods return a String object that contains the
uppercase or lowercase equivalent of the invoking String.
String toLowerCase( )
String toUpperCase( )