290 likes | 304 Views
CIS 234: Strings (click, scroll down). Dr. Ralph D. Westfall April, 2010. What Is a String?. series of characters enclosed in double quotes
E N D
CIS 234: Strings(click, scroll down) Dr. Ralph D. Westfall April, 2010
What Is a String? • series of characters enclosed in double quotes • characters can include letters (lower case and upper case), digits, special characters (spaces, punctuation marks, mathematical operators, "escape sequences," etc.) • "Kim" "137 Flower St." "a + b\n“ • it is a data type but not a primitive one
Strings in Memory • memory is assigned when a string is created • if a string's value changes, its memory location (and possibly length) changes • "anonymous" strings have a memory location but no variable name System.out.println("Total: "); //anonymous
Strings in Memory - 2 • each character in a string is identified by an offset from its memory location • 1st character is at address of string • offset = 0 • 2nd character is at string address + 1 x 2 • offset = 2 bytes (in Unicode) • 3rd is at string address + 2 x 2, etc.
Exercise • based on the spreadsheet example, make up a variable name and address table and a memory diagram for: • someone’s name • their age • how much money is in their pocket
String Class • String is a class in Java, not a primitive data type, so strings are declared with String (1st letter capitalized) • unlike other classes, don't always have to use new String myName = new String("Juan"); // ok String yourName = "Viji"; // also ok
String Class Methods • when creating a string, you create an object of the String class • can use String class methods with strings you create, by attaching a method to a string with a dot int size = myName.length(); int size = "Joan of Arcadia".length(); /* length method in String class assigns # of characters in myName object to size */
String Class Comparisons • with objects, == compares memory locations, not actual values • == wouldn't recognize exactly same string values if in different memory locations • in some situations, == test on exactly the same strings may NOT be true • to be safe, need to use String class methods instead to compare values
String Class equals Method • compares strings in same or different memory locations private String aName; private boolean test; aName = "Lee "; //includes spaces test = (aName.equals("Lee")) // false • "Lee " includes space characters test = ("Lee".equals(aName)) // another way
String compareTo Method • compares two strings letter by letter • if identical, returns 0 • otherwise returns numeric distance between 1st nonmatching characters • value is calculated as (1st – 2nd) • if 1st is less, value is negative
String compareTo Method - 2 String aName = "Li"; int distance = (aName.compareTo("Le")); // i is ASCII 105, e is ASCII 101 • aName ("Li) is 1st, "Le" is 2nd • alphabetically, "Li" comes after "Lee" • result = "Li" minus "Le" • therefore distance is positive (+4)
Practice oneName = "Lee"; twoName = "Lidia"; threeName = "Larry"; test = (oneName.equals(twoName)) // test = ? num = (threeName.compareTo(oneName)); // num= ?
String length Method size = myEmail.length(); • make sure that object you attach length method to is a String, not an array of Strings • possible to have an array (group with same name) of strings • length is also a method of Array class, so would return size of array instead of string
String indexOf Method • finds first location of a specific character within a string • 1st character has index of 0 • if character not found, returns –1 (minus) hisEmail = "Enfei@fish.net"; at = hisEmail.indexOf('@'); // at = ?? can do this in Excel too
String charAt Method • returns character at offset (integer) provided in argument String twoName = "Lidia Papadakis"; char firstLetter = twoName.charAt(0); char secondLetter = twoName.charAt(1);
Practice fourthName = "Hsing-Chen"; num = fourthName.length(); // num = ? num2 = fourthName.indexOf ('i'); //num2 = ? myChar = fourthName.charAt(4); //myChar= ?
startsWith, endsWith Methods • compare start or end of string with another string value • return true or false aString = "vegetate"; test1 = aString.startsWith("b"); // ?? test2 = aString.endsWith("ate"); // ??
String replace Method • replaces all occurrences of 1 character with another • cf. "Replace all" in Word, Excel, etc. • arguments are character to find, character to replace it with oneString = "some hot"; twoString = oneString.replace('o', 'a'); // twoString = ?
String substring Method • returns part of another string • arguments are starting position (offset) and "boundary" position (end +1) oneString = "separate"; twoString = oneString.substring(3, 7); // twoString = ? //notes on slides 8 to 18
String Class Case Methods • toUpperCase converts to capital letters aName = aName.toUpperCase(); • used for "shouting" in Mouth class • toLowerCase converts to lower case • used for "quiet" in Mouth class • Makes it possible to ignore case of inputs • Makes ANA the same as Ana and ana
Numbers to Strings • toString converts other data types to strings long bigNum = 1234243342; strBigNum = toString(bigNum); // stringBigNum = "1234243342"
Strings to Numbers • use data type "wrapper" class methods • wrapper classes make it possible to treat "primitive" data types like they were classes int num = Integer.parseInt("135"); • Integer class is wrapper for int data type double dNum = Double.valueOf("1.2343"); • Double class is double data type wrapper
Review Questions • only alphabetical letters can be in Strings, not numerical ones: T or F? • Strings are primitive variables: T or F? • why is the s capitalized in String? • where else are first letters capitalized? • what punctuation marks enclose values in a String?
Review Questions - 2 • what is the recommended way to check if two Strings are equal? • int distance = ("J".compareTo("Lo")); • how do we find the length of a String? • how do we pick out parts of a String? • what are the arguments we need for this? • who is richer—Scrooge McDuck or Flintheart Glomgold—and why? (artist)
Appendix 1: StringBuffer Class • problems with String class • every time you change a string's value, Java creates a new string • the length of a string is set when it is created, and can't be changed • StringBuffer class deals with these problems • stored in same place, size can increase
StringBuffer Constructors • 3 constructors (note signatures) • StringBuffer() creates an empty StringBuffer object with space for 16 characters • StringBuffer(int length) new object has space for # of characters in argument • StringBuffer(String s) creates object with string s characters plus space for 16 more
StringBuffer Methods • append method adds new string to end of previous one • insert method puts characters in between existing characters, starting at specified location • for both, if not enough space, Java will automatically expand the buffer object
Appendix 2: Inputting #s > 9 // (declarations omitted) newChar = (char) System.in.read(); while (newChar >= '0' && newChar <= '9') { inString = inString + newChar; // "adding" newChar = (char)System.in.read(); } inNum = Integer.parseInt(inString);
Questions re Previous Slide • why does code input newChar before loop starts? • why does code input newChar after adding newChar to inString? • what happens when user hits Enter key?