COP 2500 Spring 2012

Lab #9: Strings

Home Labs Lecture Notes
 
Deliverables: Email your instructor showing what you have completed. You can get partial credit even if not fully completed with the lab.

Introduction: The goal of this assignment is to allow you to become familiar with properties and methods of the String objects. You will be able to change their appearance and manipulate them.

Formatting Strings
The String object formatting methods (functions that modify a String), with result displayed:

Manipulating Strings
var count = 0;
for (i=0;i< str2.length;i++)
{
if(str2.charAt(i) == 'a')
count++;
}

Arrays of Strings
The join method of Arrays joins all elements of an array into a string, which can be separated by a String you input.
var str3 = new Array(3);
str3[0] = "Java";
str3[1] = "Script";
str3[2] = "Program";

Adding New Methods
The prototype method adds a method to an Object (such as an Array or String). Access the Object's own methods with this. After adding a method with prototype, any Object of that type can now access the method.
String.prototype.findletter = function findletter(l)
{
return this.indexOf(l);
}
var str4 = "addmethod";
var str5 = "worksforallstrings";


Excercise
    Part 1
  • Create a String object containing "Jose lived in San Jose for many years."
  • Find the index for the second Jose.
  • Get the substring 'ear' from years.

  • Part 2: Counting Occurrences
  • Add a new method to String called countOccurrences which counts the occurrences of a letter in a string which takes in the letter to search for, and returns the count.
  • Display the number of occurrences of the letter e in "Jose lived in Sane Jose for many years." output by your new counting method.

  • Part 3: Generalizing Formatting
  • Add a new method to String called format which takes in some color, typeface (italic, bold, striked or none), fontsize, and whether to display in upper or lower case.
  • Using your new formatting method, format the String "Jose lived in San Jose for many years." as blue, italic, size 12, and all uppercase.