230 likes | 476 Views
Stringing Along in Java. A Java Class in Action. CS 102-02 Lecture 6-1. Today in a Nutshell. Characters and strings Methods on strings Substrings Buffered strings. "What’s a String?". A string is a bunch of characters treated as a single unit Characters are the building blocks
E N D
Stringing Along in Java A Java Class in Action CS 102-02 Lecture 6-1
Today in a Nutshell • Characters and strings • Methods on strings • Substrings • Buffered strings
"What’s a String?" • A string is a bunch of characters treated as a single unit • Characters are the building blocks • ASCII is a 7-bit encoding (variations are 8-bit) • Unicode is a 16-bit encoding
Global Strings • Globalization makes characters complicated • Locales • Locale object represents a specific geographical, political, or cultural region • Locale-sensitive operations use a Locale object to tailor information for the user • Example: Displaying a number
Strings in Java • String is a class in Java • Strings are constant (values cannot be changed after they are created) • Set of characters "Lisa Simpson" is an anonymous string (aka, string constant or literal string) • "A" is a string, 'A' is a character
Here, There and Everywhere • Strings are very common in programming • Text is everywhere • Strings are good for short pieces of text • String manipulation • Find the length of strings • Extract characters • Compare strings
How Long? • Use length() to find out how long a string is String test; test = new String("The quick, brown"); System.out.println("Length of test is: " + test.length()); • Works on anonymous strings too: System.out.println("'Lisa Simpson' is: " + "Lisa Simpson".length() + " characters long.");
Strings are Character Sequences • Grab individual characters with charAt() public char charAt(int index) • A quick example: for (int nextChar = 0; nextChar < test.length(); nextChar++) { g.drawString(test.charAt(nextChar), xPos, yPos+(15*nextChar)); }
More for Your Money • Get more than one character at atime with getChars() public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) • Copies characters from this string into the destination character array. • First character is at index srcBegin • Last character to be copied is at index srcEnd-1 • Subarray of dst starting at index dstBegin and ending at index: dstbegin + (srcEnd-srcBegin) - 1
Comparing Strings • What do the concepts ==, <= and >= mean for strings? • Compare initial characters in a string • Different than numbers • Upper and lower case • Java uses lexicographic ordering
Comparing Strings • Are two strings equal (including upper and lower case)? public boolean equals(Object anObject) "ABC".equals("ABC") is true "ABC".equals("abc") is false • If you want to ignore case, use: public boolean equalsIgnoreCase(String anotherString)
==, < or > ? • Comparing two strings: public int compareTo(String anotherString) • 0 if the argument string is equal to this string • Less than 0 if this string is lexicographically less than the string argument • Greater than 0 if this string is lexicographically greater than the string argument
Comparing Substrings • Use regionMatches to heck for equality within two strings public boolean regionMatches(int toffset, String other, int ooffset, int len) • Example "A quick, brown fox".regionMatches(7, "An old, brown banana", 6, 7)
Comparing Regions Offset == 7 "A quick, brown fox" 0123456789 "An old, brown banana" Length == 7 Offset == 6
Finding the Substring of Your Dreams • Find characters (and sequences of characters) within strings • Looking for characters? indexOf(int) indexOf(int, int) indexOf(String) indexOf(String, int) lastIndexOf(int) lastIndexOf(int, int) lastIndexOf(String) lastIndexOf(String, int)
Getting the Index • Examples "abcdefabc".indexOf((int) 'c')is 2 "abcdefabc".indexOf("bc")is 1 "abcdefabc".lastIndexOf("bc")is 7 "abcdefabc".indexOf((int) 'a', 5)is 6
Substrings • A substring is a string within a string • Two substring methods • public String substring(int beginIndex) Starts with index and grabs the remainder of the string • public String substring(int beginIndex, int endIndex) • Includes character at beginIndex, but not the character at endIndex
The String's the Thing • Strings are an easily understandable format • Need to convert a variable to something readable? Try valueOf()! boolean char char[] char[], int, int double float int long Object • For Object, valueOf() returns the same as obj.toString() • A string that "textually represents" this object
Replacing String Characters • Replace one character with another in a new string replace(char oldChar, char newChar) Example: String name = "Babe, toe soeep-oerding pig"; name.replace('o', 'h');
Case Conversion • Make a copy of a string, all in one case • Handy for enforcing consistency: always switch strings to upper case or lower case public String toLowerCase(Locale locale) public String toLowerCase() public String toUpperCase(Locale locale) public String toUpperCase()
Trimming Away Excess String • Throw away leading and trailing whitespace • Makes matching more reliable public String trim() • All characters that have codes less than or equal to '\u0020' (the space character) are considered to be white space
Buffer the String Slayer • Strings are immutable objects • Methods that seem to modify a string actually create a new string object • Buffered strings can be modified • Buffered strings have two "lengths" • Current length of the string • Buffer length (capacity)
More on String Buffers • Strings buffers are great when you need to do extensive string manipulation • Handy for communications between programs • Two programs can communicate with one another (for example, email) • Store incoming and outgoing messages in buffers