Arrays and Strings

advertisement
Arrays and Strings
1
CSA 1012 - Joseph Cordina (C)
Java/C# Arrays
•
•
•
An array is a fixed-size collection
of data, all of the same class type
An array in Java/C# is actually an
object of a special class type
To declare an array variable one
needs to specify the class type:
(Java)
Integer data[] = null;
– alternate syntax (Java/C#):
Integer[] data = null;
•
•
Note that one does not need to
specify the size just yet.
The array variable will be able to
point to an object which can hold
multiple references to specific
objects
CSA 1012 - Joseph Cordina (C)
2
Java/C# Arrays (contd.)
• After declaration one needs to
initialise the object:
Character data[];
data=new Character[30];
• The object pointed to by data
is now able to store 30
references of type Character.
• Note that the array merely holds
class-type variables and not
objects themselves.
• The default value of each
reference item is set to null.
3
CSA 1012 - Joseph Cordina (C)
Array Constants
• One can initialise the contents
of the array to be non-null.
• An array constant provides
initial values for its elements :
Integer i = new
Integer(3);
Integer[] int_array
= {new Integer(4),i};
• This creates an array int_array
of 2 references to objects of
type Integer at indices 0..1
• Array constants may appear
only in initialisation
4
CSA 1012 - Joseph Cordina (C)
Using Arrays
• The [ ] operator, applied to an
array variable gives the value of
an element of the array:
Integer array[] =
new Integer[20];
array[0] = new Integer(7);
System.out.println(
array[0].intValue());
• Legal index range is
0..length-1
• If an out-of-bounds index is
applied to an array, Java
produces a run-time error
5
CSA 1012 - Joseph Cordina (C)
Using Arrays (contd.)
• Every array has an integer data
number length/Length that
contains the number of elements in
the array (remember arrays are
objects themselves yet with special
terminology):
Integer arr[] = new Integer[100];
for (Integer i=new Integer(0);
i.intValue()<arr.length;
i=new Integer(i.intValue()+1))
{
arr[i.intValue()] =
new Integer(i.intValue()*2);
}
- Length/Length is a value that
cannot be changed. Once an array’s
size is set, its size cannot be changed
6
CSA 1012 - Joseph Cordina (C)
Copying Array Elements
• Use the method
System.arraycopy()/Array
.Copy() to copy elements from
one array to another.
• The definition of this method is as
follows:
public static void arraycopy(
public static void Copy(
Array src,
int src_position,
Array dst,
int dst_position,
int length)
• Both the source and destination
arrays must have been initialised and
their size should be enough to fit all
entries.
• If you try to copy one class type
array to another, a run time error will
occur.
7
CSA 1012 - Joseph Cordina (C)
Copying Array Elements
(contd.)
Example in Java:
Integer[] arr1={ … };
Integer[] arr2=new Integer
[arr1.length];
System.arraycopy(arr1, 0, arr2, 0,
arr1.length);
C#:
Integer[] arr1={ … };
Integer[] arr2=new Integer
[arr1.Length];
Array.Copy(arr1, 0, arr2, 0,
arr1.length);
• Any class type array may be copied
• If range exceeds bounds of either
array, run-time error results:
Java: IndexOutOfBoundsException
C# : IndexOutOfRangeException
8
CSA 1012 - Joseph Cordina (C)
Methods returning
Arrays
• A method can also return an
array
example.
static Integer[] array =
new Integer[20];
public static Integer[] getArray()
{
return array;
}
• Note that a reference to the
array is returned and not a copy
9
CSA 1012 - Joseph Cordina (C)
String Objects
•
•
A String represents a Character
array of arbitrary length
A Java/C# String is an object of
type String and can be
represented as a series of
characters within double quotes.
“This is a String object”
•
•
Strings can be used as any other
type of Java/C# object.
In fact one can have arrays of
strings and one can create new
strings at will.
10
CSA 1012 - Joseph Cordina (C)
String Objects (contd.)
Example:
void printMsg(String userName)
{
String msg1 = “Hello,” ;
String msg2 = userName;
if (msg2 == null)
msg2 = “anonymous user”;
System.out.println(msg1 + msg2);
}
• Strings are immutable and their
internal value can never be
changed. The methods
associated with a String object
always return a new String and
do not modify the original
String.
11
CSA 1012 - Joseph Cordina (C)
String Methods
• To inquire the length of a string:
String str =“Another string”;
C#
System.out.println(str.length());
Java
Console.WriteLine(str.Length());
• Note that String is not an array as in
other programming languages, but
an object
• To extract a character of a string:
Java:
Character first =
new Character(str.charAt(0));
Character last =
new Character(
str.charAt(len – 1));
C#:
Character first = new
Character(str[0]);
Character last =
new Character(
str[len – 1]);
12
CSA 1012 - Joseph Cordina (C)
String Methods (contd.)
• To extract a substring:
String sl=str.substring(0,7);
// sl is now “Another”
String s2=str.substring(2,7);
// s2 is now “other”
String s3=str.substring(8);
// s3 is now “string”
13
CSA 1012 - Joseph Cordina (C)
Java String Comparison
• String variables behave like
other class-type variables
when compared using == or
!=:
if (s1 == s2)
{ …
// True only if the two variables
// refer to the same object
// regardless of contents!
}
• In C# == compares the contents.
14
CSA 1012 - Joseph Cordina (C)
Java/C# String
Comparison (contd.)
•
This is Java Code; C# code is very similar. Refer to
Documentation
String s1,s2;
s1 = “Hello”; s1=s2;
if (s1.equals (s2))
{…}
if (s1.equalsignoreCase(s2))
{…}
if (s1.startsWith (s2))
{…}
if (s1.endsWith (s2))
{…}
if (s1.compareTo(s2)>0 ) {
String temp = s1;
s1 = s2;
s2 = temp;
}
• Refer to Java/C# Documentation for other String
methods together with their explanation.
15
CSA 1012 - Joseph Cordina (C)
String Searching
• This is Java Code; C# code is
very similar. Refer to
Documentation
• indexOf() returns the
position of the character given
in a string or –1 if not found.
• Class String provides methods
that search a string for a
character:
if (s1.indexOf(‘:’) >= 0)
{ … }
String suffix =
s1.subString (
s1.lastIndexOf (‘.’));
16
CSA 1012 - Joseph Cordina (C)
String Searching (contd.)
• This is Java Code; C# code is very
similar. Refer to Documentation
• Space Counter
Integer spaceCount = new Integer(0);
Integer index = new Integer
(s1.indexOf(‘ ‘));
while (index.intValue() >= 0)
{
spaceCount=new Integer(
spaceCount.intValue()+1);
index= new Integer(
s1.indexOf(‘ ‘,
index.intValue()+1));
}
• If looking for a substirng:
Integer index = new Integer(
s1.indexOf(“that”));
17
CSA 1012 - Joseph Cordina (C)
Other String Methods
• This is Java Code; C# code is very
similar. Refer to Documentation
• Class String provides methods
for manipulating string data
• Each method demonstrated
below creates a new String
– it does not modify its String:
s2
s2
s2
//
//
s2
= s1.replace (‘ ‘,‘_’);
= s1.toLowerCase();
= s1.toUpperCase();
remove white space before
or after string
= s1.trim ();
18
CSA 1012 - Joseph Cordina (C)
String Concatenation
• This is Java Code; C# code is
very similar. Refer to
Documentation
• The concat() method
concatenates two strings,
producing a new String:
String fname = s1.concat (“.txt”);
• The String “+” operator is more
commonly used:
String fname = s1 + “.txt”;
String path = s1 + “/” + s2 + “.txt”;
19
CSA 1012 - Joseph Cordina (C)
Converting Objects to
Strings
• If an operand to a String
concatenation operator is not a
String, the compiler converts it
to a String.
– This is done by calling the
toString() method of classtype objects
• In addition, any string can be
converted into another class
type variable.
– We covered this topic when
discussing inputs.
20
CSA 1012 - Joseph Cordina (C)
Download