1 / 29

CIS 234: Strings (click, scroll down)

CIS 234: Strings (click, scroll down). Dr. Ralph D. Westfall April, 2010. What Is a String?. series of characters enclosed in double quotes

bhutchinson
Download Presentation

CIS 234: Strings (click, scroll down)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CIS 234: Strings(click, scroll down) Dr. Ralph D. Westfall April, 2010

  2. 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

  3. 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

  4. 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.

  5. 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

  6. 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

  7. 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 */

  8. 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

  9. 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

  10. 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

  11. 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)

  12. Practice oneName = "Lee"; twoName = "Lidia"; threeName = "Larry"; test = (oneName.equals(twoName)) // test = ? num = (threeName.compareTo(oneName)); // num= ?

  13. 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

  14. 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

  15. 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);

  16. Practice fourthName = "Hsing-Chen"; num = fourthName.length(); // num = ? num2 = fourthName.indexOf ('i'); //num2 = ? myChar = fourthName.charAt(4); //myChar= ?

  17. 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"); // ??

  18. 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 = ?

  19. 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

  20. 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

  21. Numbers to Strings • toString converts other data types to strings long bigNum = 1234243342; strBigNum = toString(bigNum); // stringBigNum = "1234243342"

  22. 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

  23. 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?

  24. 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)

  25. 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

  26. 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

  27. 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

  28. 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);

  29. 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?

More Related