Difference between revisions of "Arrays of Strings"

From CompSciWiki
Jump to: navigation, search
m (Updated spacing of code.)
 
(28 intermediate revisions by 4 users not shown)
Line 1: Line 1:
{{Template:1010Topic|Chapter_TOC=[[More With Arrays]] > [[Arrays of Strings]]|Introduction=This chapter assumes that you have already read the chapter on Strings and the chapter on Arrays.  This section includes what an array of strings is, how to define and initialize an array of strings, how to deal with null strings and several examples of processing arrays of strings.
+
{{Template:1010Topic
 +
|Chapter_TOC=[[More With Arrays]] > [[Arrays of Strings]]
 +
|Previous=[[Partially Filled Arrays]]
 +
|Next=[[Searching Arrays]]
 +
|Body=
  
|Overview=This section describes:<br>1. What an array of Strings is<br>2. How to initialize and declare an array of Strings<br>3. Process an arrays of Strings<br>4. How to deal with null strings}}
+
==Introduction==
 +
This chapter assumes that you have already read the chapter on [[Strings]] and the chapter on [[Arrays]]. This section includes what an array of Strings is, how to define and initialize an array of Strings, how to deal with null Strings and how to use String methods on an String Array indexes.
  
== What are arrays of Strings? ==
 
  
Recall that an array is a contiguous group of some data type, and a String is text represented as a list of characters. An array of Strings, then, is a contiguous group of Strings, each of which contains text.
+
== What are Arrays of Strings? ==
  
Also recall that a String is an object type, not a primitive type. That means that a String is represented by a reference that points to a value in memory. So, unlike arrays of primitive value types (like int, char, etc.) a String array is an array of references.
+
An array is a data structure whose indexes contain a specific data type. A String is an object where text is represented as a list of characters. An array of Strings is an array where each index contains a String object.  Figure 1 displays an array of Strings containing brands of soft drinks.
  
== How do I use arrays of Strings? ==
+
[[Image:Arrays.Strings.Fig.1.jpg]]
  
String arrays are declared like any other array:
+
== Define and Initialize an Array of Strings ==
 +
You need to define an array of Strings before you can manipulate and process its contents.  All String objects in an array of Strings are initialized to the value null the array of Strings is initialized. Null is a special value that signifies that an object type currently has no value.  Figure 2 displays what our softDrinks array of Strings looked like when it was initialized.
  
<pre>String[] ouchMyFace;</pre>
+
{{CodeBlock
 +
|Code=
 +
String[] softDrinks; // defines a String array named "softDrinks"
  
You can access individual Strings in exactly the same way as you do with any other array. Observe:
+
softDrinks = new String[5];  // this initializes softDrinks to be an array of Size 5
 +
}}
  
<pre>
+
[[Image:Arrays.Strings.Fig.2.jpg]]
String[] ouchMyFace = new String[5]; // Creates an array of 5 Strings -- These Strings are initialized to null.
+
  
// So, let's make some Strings!
+
The code below displays how to define, initialize and access indexes of the array of Strings shown in figure 1.
ouchMyFace[0] = "Ouch,";
+
ouchMyFace[1] = "my";
+
ouchMyFace[2] = "face!";
+
ouchMyFace[3] = "It's";
+
ouchMyFace[4] = "on fire!";
+
  
// Now, let's print them.
+
{{CodeBlock
for( int i = 0; i < ouchMyFace.length; i++ ) {
+
|Code=
    System.out.print( ouchMyFace[i] + " " ); // Prints a space after each String
+
public static void main(String[] args)
}
+
{
</pre>
+
  // Option 1 for Defining, Initializing and Setting Contents
 +
  String[] softDrinks; // defines a String array named "softDrinks"
  
The output of this little program will be the text "Ouch! My face! It's on fire! ". Note the space after the last exclamation point -- we could add additional code to fix this, if necessary.
+
  softDrinks = new String[5];  // this initializes softDrinks to be an array of Size 5
  
Since Strings contain more than one character, you can also get at individual characters by using charAt(). Observe the next part of our example program:
+
  softDrinks[0] = "Coca Cola"; // sets index 0 of softDrinks to "Coca Cola"
 +
  softDrinks[1] = "Pepsi"; // sets index 1 of softDrinks to "Pepsi"
 +
  softDrinks[2] = "Dr. Pepper"; // sets index 2 of softDrinks to "Dr. Pepper"
 +
  softDrinks[3] = "Sprite"; // sets index 3 of softDrinks to "Sprite"
 +
  softDrinks[4] = "7up"; // sets index 4 of softDrinks to "7up"
 +
  softDrinks[5] = "Orange"; // sets index 5 of softDrinks to "Orange"
  
<pre>
+
  // Option 2 for Defining, Initializing and Setting Contents
// Note: length() is a method in String that returns the number of characters in the String
+
  String[] softDrinks2 = {"Coca Cola","Pepsi","Dr. Pepper","Sprite","7up","Orange");
for( int i = 0; i < ouchMyFace[0].length(); i++ ) {
+
    System.out.print( ouchMyFace[0].charAt[i] ); // Gives you each individual character
+
 
}
 
}
</pre>
+
}}
  
This piece of code will print "Ouch,". Notice that there is no space at the end, since the original String had no spaces and we did not add any spaces.
 
  
== What should I watch out for? ==
+
== Using String Methods on Array Indexes ==
 +
Each index of an array of Strings contains a String object.  This means that all of the String methods you learned about can be applied to every index of an array of Strings. 
  
=== null Strings ===
+
Example 1: Print the length of every String in our SoftDrinks array (shown in Figure 1).
 
+
{{CodeBlock
The first "gotcha" is that all Strings in an array of Strings is initialized to the value null. Null is a special value that means that a variable of an object type currently has no value; that is, its reference points to nothing. Null is not a valid String, so you must use '==' and '!=' to check for it, rather than the .equals() method, like in this example:
+
|Code=
 
+
public printLength(String[] softDrinks)
<pre>
+
{
String[] testing = new String[2];
+
  for (int i = 0; i < softDrinks.length; i++)
 
+
  {
testing[0] = "Not null!";
+
      System.out.println("Length of the String ",softDrinks[i]," is ",softDrinks[i].length());
 
+
  }
if (testing[0] == null) {
+
  System.out.println("testing[0] is null");
+
}
+
if (testing[1] == null) {
+
  System.out.println("testing[1] is null");
+
 
}
 
}
</pre>
+
}}
 +
Notice how we accessed the array index "softDrinks[i]", then applied the "length()" method to it.  The length method was applied to every String object in our array softDrinks.  You can also apply other String methods such as charAt and subString to the String objects in array indexes.  Just remember to access the index of the String object first by using syntax like "softDrinks[i]".
  
The output will be "testing[1] is null".
 
  
Calling any method on a String that does not point to a valid value (i.e. is null) will crash your program. The following program shows you what '''not''' to do:
+
== Dealing with NULL Strings ==
  
<pre>
+
Figure 3 shows the array resulting from the code below.  Notice that there is a NULL value at index 4.  This NULL value exists because we didn't assign anything to the String object at index 4.
String[] letsCrashThis = new String[5];
+
  
// Calling a method on a string that doesn't exist (i.e. is null)
+
{{CodeBlock
System.out.println( letsCrashThis[3].charAt(0) );
+
|Code=
</pre>
+
public static void main(String[] args)
 +
{
 +
  String[] animals; // defines a String array named "animals"
  
The output will be a run-time error.
+
  animals = new String[5];  // this initializes animals to be an array of Size 5
  
=== Nested for loops ===
+
  animals[0] = "Cat"; // sets index 0 of animals to "Cat"
 +
  animals[1] = "Dog"; // sets index 1 of animals to "Dog"
 +
  animals[2] = "Bat"; // sets index 2 of animals to "Bat"
 +
  animals[3] = "Bird"; // sets index 3 of animals to "Bird"
 +
  animals[5] = "Frog"; // sets index 5 of animals to "Frog"
 +
}
 +
}}
  
A String stores multiple characters, so unlike other arrays, we often need nested for loops when dealing with arrays of Strings.
+
[[Image:Arrays.Strings.Fig.3.jpg]]
  
Observe the difference between two methods that accomplish the same goal: counting the number of 'a' characters in an array.
+
=== The Problem with NULL Values ===
  
In the first example, we are dealing with a character array.
+
Let's print the contents of animals.
  
<pre>
+
{{CodeBlock
public static int countNumberOfAs(char[] charArray) {
+
|Code=
  int count = 0;
+
public print(String[] animals)
 
+
{
  for (int i=0; i < charArray.length; i++) {
+
  for (int i=0; i < animals.length; i++)
    if (charArray[i] == 'a') {
+
  {
      count++;
+
      System.out.println(animals[i]);
    }
+
  }
  }
+
 
+
  return count;
+
 
}
 
}
</pre>
+
}}
  
In the second example, we are dealing with a String array.
+
We will encounter a problem when printing this array when i=4, because the String object at animals[4] is NULL.  We can't print NULL, so our program will crash when i=4.
  
<pre>
+
=== Fixing the NULL String Problem ===
public static int countNumberOfAs(String[] stringArray) {
+
  int count = 0;
+
  
  for (int i=0; i < stringArray.length; i++) {
+
We can fix our print method by testing for NULL values.  The '==' and '!=' operators allow us to check each index to determine if it contains a NULL value or not.  The code below shows off an improved version of our print method.
  
    for (int j=0; j < stringArray[i].length(); j++) {
+
{{CodeBlock
       if (stringArray[i].charAt(j) == 'a') {
+
|Code=
        count++;
+
public print(String[] animals)
 +
{
 +
  for (int i=0; i < animals.length; i++)
 +
  {
 +
       if (animals[i] != NULL)
 +
      {
 +
        System.out.println(animals[i]);
 
       }
 
       }
    }
+
  }
 +
}
 +
}}
  
  }
+
When i=4 in our improved version, the if statement will evaluate and see that animals[4] == NULL and will not print.  Therefor, we avoid our program crashing like our previous print method.  The for loop will continue executing until the boolean i < animals2.length returns false.
 
+
  return count;
+
}
+
</pre>
+
  
Notice the additional nested for loop in the second example. When you are dealing with arrays of strings, you will often need nested loops like this because you have to deal with the characters in each String.
 
  
== How do arrays of Strings work? ==
+
== Section Summary ==
  
The actual Strings being stored ''are not in the array'' -- each of them is somewhere else in memory. Each element of the String array contains a reference that points to where the actual Strings are stored. You will still work with your arrays of Strings as though they are contiguous groups of Strings, but keep in mind that the elements of the array are references, not actual values.
+
Arrays of Strings are arrays where each index contains a String.  You can process many Strings at once by utilizing an array of Strings instead of declaring a lot of separate String objects. All indexes within an array of Strings are initialized to NULL.  You can manually assign String values to an array index to overwrite the NULL value.  Be careful of NULL values when processing an array of Strings.  Use the '!=' and '==' operators to check each index of an array of Strings for a NULL value.  You are able to apply String methods to each index of an array of Strings.  Make sure you access the index before applying the method. You now know what an array of Strings is, how to define and initialize an array of Strings, how to deal with null Strings and how to apply String methods to the indexes of an array of Strings.
 +
}}

Latest revision as of 23:34, 7 December 2011

COMP 1010 Home > More With Arrays > Arrays of Strings


Introduction

This chapter assumes that you have already read the chapter on Strings and the chapter on Arrays. This section includes what an array of Strings is, how to define and initialize an array of Strings, how to deal with null Strings and how to use String methods on an String Array indexes.


What are Arrays of Strings?

An array is a data structure whose indexes contain a specific data type. A String is an object where text is represented as a list of characters. An array of Strings is an array where each index contains a String object. Figure 1 displays an array of Strings containing brands of soft drinks.

Arrays.Strings.Fig.1.jpg

Define and Initialize an Array of Strings

You need to define an array of Strings before you can manipulate and process its contents. All String objects in an array of Strings are initialized to the value null the array of Strings is initialized. Null is a special value that signifies that an object type currently has no value. Figure 2 displays what our softDrinks array of Strings looked like when it was initialized.

 String[] softDrinks;  // defines a String array named "softDrinks"

softDrinks = new String[5];  // this initializes softDrinks to be an array of Size 5 

Arrays.Strings.Fig.2.jpg

The code below displays how to define, initialize and access indexes of the array of Strings shown in figure 1.

 public static void main(String[] args)
{
   // Option 1 for Defining, Initializing and Setting Contents
   String[] softDrinks;  // defines a String array named "softDrinks"

   softDrinks = new String[5];  // this initializes softDrinks to be an array of Size 5

   softDrinks[0] = "Coca Cola"; // sets index 0 of softDrinks to "Coca Cola"
   softDrinks[1] = "Pepsi"; // sets index 1 of softDrinks to "Pepsi"
   softDrinks[2] = "Dr. Pepper"; // sets index 2 of softDrinks to "Dr. Pepper"
   softDrinks[3] = "Sprite"; // sets index 3 of softDrinks to "Sprite" 
   softDrinks[4] = "7up"; // sets index 4 of softDrinks to "7up"
   softDrinks[5] = "Orange"; // sets index 5 of softDrinks to "Orange"

   // Option 2 for Defining, Initializing and Setting Contents
   String[] softDrinks2 = {"Coca Cola","Pepsi","Dr. Pepper","Sprite","7up","Orange");
} 


Using String Methods on Array Indexes

Each index of an array of Strings contains a String object. This means that all of the String methods you learned about can be applied to every index of an array of Strings.

Example 1: Print the length of every String in our SoftDrinks array (shown in Figure 1).

 public printLength(String[] softDrinks)
{
   for (int i = 0; i < softDrinks.length; i++)
   {
      System.out.println("Length of the String ",softDrinks[i]," is ",softDrinks[i].length());
   }
} 

Notice how we accessed the array index "softDrinks[i]", then applied the "length()" method to it. The length method was applied to every String object in our array softDrinks. You can also apply other String methods such as charAt and subString to the String objects in array indexes. Just remember to access the index of the String object first by using syntax like "softDrinks[i]".


Dealing with NULL Strings

Figure 3 shows the array resulting from the code below. Notice that there is a NULL value at index 4. This NULL value exists because we didn't assign anything to the String object at index 4.

 public static void main(String[] args)
{
   String[] animals;  // defines a String array named "animals"

   animals = new String[5];  // this initializes animals to be an array of Size 5

   animals[0] = "Cat"; // sets index 0 of animals to "Cat"
   animals[1] = "Dog"; // sets index 1 of animals to "Dog"
   animals[2] = "Bat"; // sets index 2 of animals to "Bat"
   animals[3] = "Bird"; // sets index 3 of animals to "Bird" 
   animals[5] = "Frog"; // sets index 5 of animals to "Frog"
} 

Arrays.Strings.Fig.3.jpg

The Problem with NULL Values

Let's print the contents of animals.

 public print(String[] animals)
{
   for (int i=0; i < animals.length; i++)
   {
      System.out.println(animals[i]);
   }
} 

We will encounter a problem when printing this array when i=4, because the String object at animals[4] is NULL. We can't print NULL, so our program will crash when i=4.

Fixing the NULL String Problem

We can fix our print method by testing for NULL values. The '==' and '!=' operators allow us to check each index to determine if it contains a NULL value or not. The code below shows off an improved version of our print method.

 public print(String[] animals)
{
   for (int i=0; i < animals.length; i++)
   {
      if (animals[i] != NULL)
      {
         System.out.println(animals[i]);
      }
   }
} 

When i=4 in our improved version, the if statement will evaluate and see that animals[4] == NULL and will not print. Therefor, we avoid our program crashing like our previous print method. The for loop will continue executing until the boolean i < animals2.length returns false.


Section Summary

Arrays of Strings are arrays where each index contains a String. You can process many Strings at once by utilizing an array of Strings instead of declaring a lot of separate String objects. All indexes within an array of Strings are initialized to NULL. You can manually assign String values to an array index to overwrite the NULL value. Be careful of NULL values when processing an array of Strings. Use the '!=' and '==' operators to check each index of an array of Strings for a NULL value. You are able to apply String methods to each index of an array of Strings. Make sure you access the index before applying the method. You now know what an array of Strings is, how to define and initialize an array of Strings, how to deal with null Strings and how to apply String methods to the indexes of an array of Strings.

Previous Page: Partially Filled Arrays Next Page: Searching Arrays