Lecture 12
Strings
These
notes introduce you to some Java classes used for creating and
manipulating characters and strings.
Introduction
Java has three classes
that can be used for manipulating characters and strings;-
-
Character :
A class that can hold a single character
-
String :
A class that can hold multiple characters. String objects
CANNOT be changed.
-
StringBuffer :
A class that can hold multiple characters. StringBuffer objects
CAN be changed.
Characters
Characters are
specified using the single quote mark ' - usually located blow the @
symbol on your keyboard. I.e.
'a'
This specifies a
single 'a' character.
This following is
invalid because it does not specify a single keyboard character:-
'ab'
Here are some more
valid characters:-
'1'
'w' '%' '\n'
the last character '\n'
denotes a newline character.
You may be used to creating
the primitive char data types, i.e.
char ch = 'a';
but you can use the Character
class instead if you want a Character object:-
Character
ch = new Character ('a');
String
Class
Strings are sequences of
Unicode characters. In Java we use the String class and
it's methods for working with String objects. The String
class is used for creating strings whose value will NOT change. If you want to
be able to modify a String after you have created it then you must
use the StringBuffer class instead.
Creating
Strings
Strings
are specified by placing characters between double quotes.
Here are some valid Strings :-
"hello"
"1234" "I am 3"
Often Strings
are created from String literals:-
System.out.println("Hello
World!");
In this case the String
"Hello World " is created for you and then destroyed after
the line is executed. You do not have a permanent reference to the String
"Hello World ". You can create a string with a
variable referencing it in two ways.
Normally we create
objects in Java using the new keyword. We can create String
objects in the same way-
String str
= new String ("Hello World!");
But there is a
shortcut way of creating String objects without using the new
keyword:-
String str
= "Hello World!";
In both examples given
I have a variable str which references a String
object with the value "Hello
World!"
String
Methods Overview
Here are some
useful methods you can use with Strings .
~~String
Length~~
|
find
the number of characters in the String
|
~~Comparing
Strings~~
|
returns
true if one String has the same value as another String (I.e. have the same
set of characters)
|
|
returns
true if one String has the same value as another String str ignoring case
considerations (I.e. have the same set of characters)
|
~~Searching
Strings~~
|
returns
the index of the first occurrence of char ch or String str within a
String.
|
|
returns
the index of the first occurrence of char ch or String str within a String,
starting the search at the specified index.
|
|
returns
the index of the last occurrence of char ch ore String str within a
String.
|
|
returns
the index of the last occurrence of of char ch or String str within a String,
starting the search backwards from the specified index.
|
~~Extracting
characters and substrings from Strings~~
|
returns
a new String which is a substring of the original String starting at the
specified beginIndex.
|
|
returns
a new String which is a substring of the original String starting at the
specified beginIndex and ending at the specified endIndex.
|
|
returns
the character at the specified index.
|
~~Converting
other data types to Strings~~
|
returns
the String representation of the argument. the argument may be a
boolean, character, double, float, int, or long.
|
Now
let's have a look at some of these methods in more detail.
String
Concatenation
You can create new String
by joining (concatenating) other Strings together using the +
operator. Here is an example:-
String str1
= "Hello";
//
note the space before the W in World
String
str2 = " World!";
System.out.println(str1
+ str2);
This would display "Hello
World!" .
Or we could have used
a third String variable:-
String
str3 = str1 + str2;
System.out.println(str3);
When you use the
+ concatenation operator, if one of the operands is a String
but the other operand is a number then Java will attempt to convert
the number to a String and then join the two, i.e.
Expression |
Resultant Value |
"1" + 2 |
"12" |
"1" + 2 + 3 |
"123" |
1 + 2 |
3 //this is not a String |
"I am " + 3 |
"I am 3" |
String
Length
You can find out the
number of characters in a String using the length()
method:-
String
str1 = "I am a string";
System.out.println(str1.length());
//prints 13
Try copying, compiling
and running the following code:-
import
java.awt.*;
import javax.swing.*;
public class StringLength extends JApplet {
public void init() {
// Create two string objects
String str1
= new String ("I am a string");
String str2 = new
String ("I am a string");
JOptionPane.showMessageOption(this,
"The length of str1 is " + str1.length());
}
}
|
String
Comparison
Let's have
another look at some methods used for comparing Strings .
~~Comparing
Strings~~
|
returns
true if one String has the same value as another String (I.e. have the same
set of characters)
|
|
returns
true if one String has the same value as another String str ignoring case
considerations (I.e. have the same set of characters)
|
So, you can compare Strings
to see if one Strings value matches another using the equals()
method:-
String
str1 = new String ("I am a string");
String
str2 = new String ("I am a string");
if
( str1.equals(str2) ) //would return true
You may
come across expressions such as:-
if
( str1 == str2 )
but you
may not get the result you are after.
To compare
Strings for equality, DON'T use == . The ==
operator checks to see if two objects are exactly the same object,
whereas the equals() methods checks to see if two String
objects contain the same value (have exactly the same characters in
them).
Here is
an example:-
//returns
false because str1 is not the same object as str2
if
( str1 == str2 )
Now try copying,
compiling and running the following code:-
import
java.awt.*;
import javax.swing.*;
public class StringCompare extends JApplet {
public void init() {
// Create two string objects
String str1
= new String ("I am a string");
String str2 = new
String ("I am a string");
if (
str1.equals(str2) )
JOptionPane.showMessageOption(this,"str1 equals str2");
else
JOptionPane.showMessageOption(this,"str1 does not equal
str2");
}
}
|
Searching
Strings
Let's have
another look at some methods used for searching Strings .
~~Searching
Strings~~
|
returns
the index of the first occurrence of char ch or String str within a
String.
|
|
returns
the index of the first occurrence of char ch or String str within a String,
starting the search at the specified index.
|
|
returns
the index of the last occurrence of char ch ore String str within a
String.
|
|
returns
the index of the last occurrence of of char ch or String str within a String,
starting the search backwards from the specified index.
|
You can search a String
for a particular character or set of characters using...
For example:-
"I
am a string". indexOf ( 'a');
returns the number 2
since this is the location of the first occurrence of 'a' in
"I am a string". You should note that index
numbers start at 0 and not 1 .
You can also use indexOf
to locate the first occurrence of a set of characters (a String )
within another String :-
"I
am a string".indexOf ("I am");
returns the number 0
since this is the location of the first occurrence of "I am"
within
"I am a string".
Now:-
"I
am a string". lastIndexOf ( 'a');
returns the number 6
since this is the location of the last occurrence of 'a' in
"I am a string".
if
the specified character or set of characters cannot be found...
then both indexOf
and lastIndexOf return the value -1 .
|
There is an
alternative way of using the indexOf method. You can specify
where in the String the method should start searching for the
character:-
"I
am a string".indexOf ('a'); // returns 2
but
"I
am a string".indexOf ('a',3); // returns 6
since I specified that
the search for the character 'a' should start at index 3
within the string "I am a string".
You can also search
for a set of one or more characters (a String ) within another String,
specifying where to start the search from:-
"I
am a string".indexOf ("a",3); // returns 6
String
Extraction
Let's have
another look at some methods used for extracting characters and substrings from Strings .
~~Extracting
characters and substrings from Strings~~
|
returns
a new String which is a substring of the original String starting at the
specified beginIndex.
|
|
returns
a new String which is a substring of the original String starting at the
specified beginIndex and ending at the specified endIndex.
|
|
returns
the character at the specified index.
|
You can extract a
character from a String
using the charAt method:-
For example:-
//
ch is assigned the character 'a'
char
ch = "I am a string".charAt(5);
Here is another
example:-
String
str = "I am a String";
//
ch is assigned the character 'a'
char
ch = str.charAt(5);
You can extract a
substring from a String
using the subString method:-
For example:-
//
newStr is assigned the String "a string"
String
newStr = "I am a string".subString(5);
Here subString(5)
specifies a substring of "I am a string" starting at
index 5 , giving a new String
"a string" . The variable newStr is
assigned to reference this substring.
Here is another
example:-
String
str = "I am a String";
//
newStr is assigned the String "a string"
String
newStr = str.subString(5);
As we have seen, when
using the subString method we must specify a starting index from
which to extract a new string. We can also specify an end index:-
//
newStr is assigned the String "am"
String
newStr = "I am a string".subString(2,4);
Converting
To a String
Let's have
another look at methods used for converting other data types to Strings
~~Converting
other data types to Strings~~
|
returns
the String representation of the argument. the argument may be a
boolean, character, double, float, int, or long.
|
The valueOf
method is overloaded which means it can be used to convert various types to a String .
Let's look at a few examples:-
String
s;
s
= String.valueOf(5); // integer conversion. s = "5"
s
= String.valueOf(3.141); // double conversion. s = "3.141"
s
= String.valueOf('z'); // character conversion. s = "z"
s
= String.valueOf(true); // boolean conversion. s = "true"
valueOf
is a class method
Notice
the declaration:- static String valueOf(some datatype)
The static
keyword means the method is a class method, in other words it is used
by the String class and not an instance of a String
class, i.e.
String.valueOf(5);
//notice the class String uses the valueOf method
|
Strings
Coding Example
StringBuffer
Class
A StringBuffer
is like a String, but unlike a String it CAN be
modified. If you want to
be able to modify a String after you have created it then you must
use the StringBuffer class instead.
At any point in time a
StringBuffer contains some particular sequence of characters, but
the length and content of the sequence can be changed through certain method
calls.
Creating
StringBuffers
StringBuffers
are created by using the new keyword:-
StringBuffer sb
= new StringBuffer();
This creates a StringBuffer
which is initially empty but can hold up to 14 characters.
Another way of
creating a StringBuffer
with a capacity for a stated number of characters is:-
StringBuffer sb
= new StringBuffer(30);
Yet another way of
creating a StringBuffer
is to specify the set of characters you want it to store:-
StringBuffer
sb = new StringBuffer("hello World!");
StringBuffer
Capacity
StringBuffer
objects are created with space for 16 extra characters over and
above those stored with it at creation time. If necessary, this space is
increased automatically.
|
StringBuffer
Methods Overview
Here
are some useful methods you can use with StringBuffers .
~~StringBuffer
Length~~
|
find
the number of characters in the StringBuffer
|
~~Comparing
StringBuffers~~
As
you will see, you have to convert a StringBuffer to a String
to use comparison methods
~~Searching
StringBuffers~~
As
you will see, you have to convert a StringBuffer to a String
to use searching methods
~~Extracting
characters and substrings from StringBuffers~~
|
returns
a new String which is a substring of the StringBuffer starting at the specified
beginIndex.
|
|
returns
a new String which is a substring of the StringBuffer starting at the specified
beginIndex and ending at the specified endIndex.
|
|
returns
the character at the specified index.
|
~~Modifying
StringBuffers~~
|
adds
the specified characters to the end of the StringBuffer. This method is
overloaded to accept various types - char[]. boolean, int, long. double, float,
object, String.
|
|
inserts
the specified characters into the StringBuffer at the element specified by
index. This method is overloaded so the second parameter can be a char[].
boolean, int, long. double, float, object or String.
|
|
deletes
the characters from elements startIndex to endIndex
|
|
deletes
the character at index
|
|
replace
the characters between startIndex and endIndex with the specified String s.
|
|
returns
a String equivalent of a StringBuffer
|
Now
let's have a look at some of these methods in more detail.
StringBuffer
Length
You can find out the
number of characters in a StringBuffer using the length()
method:-
StringBuffer
sb1 = new StringBuffer("cheese");
System.out.println(sb1.length());
//prints 6
StringBuffer
Extraction
Let's
have another look at some methods used for extracting characters and
substrings from StringBuffers .
~~Extracting
characters and substrings from StringBuffers~~
|
returns
a new String which is a substring of the StringBuffer starting at the specified
beginIndex.
|
|
returns
a new String which is a substring of the StringBuffer starting at the specified
beginIndex and ending at the specified endIndex.
|
|
returns
the character at the specified index.
|
You can extract a
character from a StringBuffer
using the charAt method:-
For example:-
StringBuffer
sb1 = new StringBuffer( "green cheese");
//
ch is assigned the character 'r'
char
ch = sb1.charAt(1);
You can extract a
substring from a StringBuffer
using the subString method:-
For example:-
StringBuffer
sb1 = new StringBuffer( "green cheese");
//
newStr is assigned the String "cheese"
String
newStr = sb1.subString(6);
Here subString(6)
specifies a substring of "green cheese" starting at
index 6 , giving a new String
"cheese" . The variable newStr is
assigned to reference this new String .
As we have seen, when
using the subString method we must specify a starting index from
which to extract a new string. We can also specify an end index:-
StringBuffer
sb1 = new StringBuffer( "green cheese");
//
newStr is assigned the String "he"
String
newStr = sb1.subString(7,9);
Modifying
StringBuffers
Let's
have another look at some methods used for modifiying StringBuffers .
~~Modifying
StringBuffers~~
|
adds
the specified characters to the end of the StringBuffer. This method is
overloaded to accept various types - char[]. boolean, int, long. double, float,
object, String.
|
|
inserts
the specified characters into the StringBuffer at the element specified by
index. This method is overloaded so the second parameter can be a char[].
boolean, int, long. double, float, object or String.
|
|
deletes
the characters from elements startIndex to endIndex
|
|
deletes
the character at index
|
|
replace
the characters between startIndex and endIndex with the specified String s.
|
|
replaces
the character at index with the specified character ch.
|
|
returns
a String equivalent of a StringBuffer
|
You can add one or
more characters to the end of a StringBuffer
using the append method:-
For example:-
StringBuffer
sb1 = new StringBuffer( "the cow");
sb1.append("
jumped"); //changes sb1 to "the cow jumped"
You can insert one or
more characters into a StringBuffer
using the insert method:-
For example:-
StringBuffer
sb1 = new StringBuffer( "the cow");
sb1.insert(3,
" fat"); //changes sb1 to "the fat cow"
You can delete one or
more characters from a StringBuffer
using the delete method:-
For example:-
StringBuffer
sb1 = new StringBuffer( "the cow");
//delete
the characters from index 0 to index 3
sb1.delete(0,3);
//changes sb1 to "cow"
You can delete a
single character from a StringBuffer
using the deleteCharAt method:-
For example:-
StringBuffer
sb1 = new StringBuffer( "??");
//delete
the characters from index 0 to index 3
sb1.deleteCharAt(?);
//changes sb1 to "cow"
You can replace a set
of characters within a StringBuffer using the replace
method. The section within StringBuffer specified by startIndex
to endIndex is deleted then the new string is inserted at startIndex .
For example:-
StringBuffer
sb1 = new StringBuffer( "ABCD");
//deletes
the characters from index 1 to 3 then inserts "bc"
sb1.replace(1,3,"bc");
//changes sb1 to "AbcD"
If the deleted
section is smaller than the replacement string then the Str is expanded in size
to cope with this.
For example:-
StringBuffer
sb1 = new StringBuffer( "ABCD");
//deletes
the characters from index 1 to 3 then inserts "bcd"
sb1.replace(1,3,"bcd");
//changes sb1 to "AbcdD"
You can replace a
single character within a StringBuffer using the setCharAt
method.
For example:-
StringBuffer
sb1 = new StringBuffer( "ABCD");
sb1.replace(2,'X');
//changes sb1 to "ABXD"
You can return a String
equivalent of a StringBuffer using the toString
method.
For example:-
StringBuffer
sb1 = new StringBuffer( "ABCD");
//set
newStr to reference a String with a value of "ABCD"
String
newStr = sb1.toString();
Searching
StringBuffers
There
are no methods for searching within the StringBuffer class.
You have to convert a StringBuffer to a String and
use the searching methods of the String class.
For example:-
StringBuffer
sb1 = new StringBuffer( "ABCD");
sb1.toString().indexOf("B");
//returns 1
StringBuffers
Comparison
There
are no methods for comparison within the StringBuffer class.
You have to convert a StringBuffer to a String and
use the comparison methods of the String class.
For example:-
StringBuffer
sb1 = new StringBuffer( "ABCD");
sb1.toString().equals("ABCD");
//returns true
StringBuffer
Coding Example
Try copying, compiling
and running the following code:-
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Keyboard extends JApplet implements ActionListener {
StringBuffer txtInput;//declare a StringBuffer
JTextField txtDisplay;//declare a text field
//create an array of 90 buttons
JButton[] keyArray = new JButton[90];
public void init(){
char AsciiChar; //can hold characters of ASCII code
//set layout of applet content pane
getContentPane().setLayout(new FlowLayout());
//create
an instance of a StringBuffer
txtInput = new StringBuffer("");
//create an instance of a text field
txtDisplay = new JTextField(30);
//add the text field to the applet content pane
getContentPane().add (txtDisplay);
// create grid layout panel with 4 rows without
// specifying the number of columns
JPanel akeyboard = new JPanel(new GridLayout(6,0));
// loop for creating 90 buttons
for(AsciiChar = 33; AsciiChar <= 122; AsciiChar++)
{
// create a button
JButton aButton = new JButton ( "" + (AsciiChar));
// add the button to the button array
keyArray[AsciiChar-33] = aButton;
// add each button to the panel
akeyboard.add(keyArray[AsciiChar-33]);
// add an action listener to each button
keyArray[AsciiChar-33].addActionListener(this);
// set the action command for each button
keyArray[AsciiChar-33].setActionCommand("" + (AsciiChar));
}
//add the panel to the applet content pane
getContentPane().add (akeyboard);
}
public void actionPerformed(ActionEvent e){
//append the user input to the StringBuffer
txtInput.append(e.getActionCommand());
//display the StringBuffer
contents in the text field
txtDisplay.setText(txtInput.toString());
}
}
|
That is folks!!
Now try the ? exercises
|