String ManipulationChapter 15
This chapter explains the String facilities. You have already seen some of the main methods of the String class
Introduction: Strings are very important. All programming languages have primitive character manipulation
• Java has a useful collection of methods associated with Strings. This chapter reviews the features covered earlier in the text and extends the study of String processing methods
Some situations where Strings are used:
• Display messages on screen
• Input text from user
• Store data on files (see Chapter 17)
• Searching web pages
• Hold text for word processing and editors
Using Strings: a recap
• Declare variables and provide initial values– String x, y;– String myName = “Parr”– String myCountry = new String (“Japan”);
• ( new is performed implicitly and explicitly – it does not have to be used)
• Strings may be assigned to other Strings– String x = “England”; String y = “France”;
• y = x; y = “ “; // zero length String
The concatenation operator
• int number = 123;• textField.setText (“ Value is “ + number );• Java rule: when one item is a string the others
are converted to String– int value = 2333– textField.setText ( “ value is “ + (22 + 33));– // value is 55 - what is displayed in Text field
• Appending x + “ something” // adds to end of x
Compare Strings
• if ( x.equals (y)) …// the .equals operator is used with String (not = = )
• Arrays of Strings– String [ ] cities = new String [10];– cities[ 1 ] = “Los Angles”;
The characters within Strings
• Double quote surround
• String x = “abc”;
• To display a double quote use \ character
• textField.setText ( “ A \“tricky “ \“ problem!”);
• \n is the newline character
• \t is the tab charcater
A note about the class type char
• Holds one item as a 16 bit unicode character.
• Can be compared as swiftly as int– char initial = ‘M’;– // note single quotes– char marker = ‘\n’; // \n is a single character
• Character type rarely used but is efficient
The String classString class methods
• An exception• StringIndexOutOfBounds
– Index too large or negative– See page 228 screenshot of StringTemplate program
• User keys in the Strings, result field tells if they are equal
• …if ( string1.equals(string2)) result = “They are equal.”;– else result = “They are not equal.”; …
Comparing Strings
• Methods: – equals, equalsIgnoreCase, compareTo
• equals: if (string1.equals (string2)) result = “They are equal”;
– equalsIgnoreCase: “This string” vs. “this string”– compareTo returns a result of:
• 0 = equal• negative = object precedes positive object that follows• positive = object follows
– n = ant.compareTo (“bee”); // returns a negative number (ANSI value for b greater that a)
Amending Strings
• replace– string1 = “Massassappi”.replace ( ‘i’ , ‘a’);
• Produces Mississippi
• toLowerCase– string1 = “Version 1.1” ;– result = string1.toLowerCase ( );– Produces version
• toUpperCase– string1 = “Java”;– result = string1.toUpperCase; – Produces JAVA
• trim– string1 = “ Center “;
• Result = string1.trim ( );• Produces “Center” without leading/following
spaces
Examining Strings
• length returns current number of characters– string1.length returns characters in string1– .length often used in loops with arrays
• Substrings:• Extracts a specified part of a string
– string1 = “position”;– result = string1.substring (2,5) ;– Result = sit // remember start count at zero
• charAt– char c1, c2;– Returns the character at a specified position
• string1 = “position”;• c1 = string1.charAt(1); // c1 = o // remember start
at zero!
indexOf
• Is a substring contained within a String– int n = “mississippi”.index(“is”,4);
• Sets n to 4 // start count at zero• if we tried (“is” , 5)• N set to -1 // not found
• lastIndexOf– Return rightmost occurrence of substring– int place = “//a.b.c/directory/file.lastIndexOf(“/”);– Value 17 returned – again start your count at zero
endsWith
• Does String end with a particular substring?
• boolean r = “ http://path/.endsWith (“/”);
• //sets r to true
StringTokenizer class
• If data has repeated substrings seperated by special characters splitting with stringTokenizer class more easily done
• January 21 5
• 4, 6 ,7,10,10,12,13, 15, 21, 20, 19,8
• Separators are spaces after January and commas after each number
nextToken ( )
• String example1 = “January 21 5”;
• String month, day, hours;
• stingTokenizer senddata = new StingTokenizer (example1, “ “);
• month = sumData.nextToken( ); day = sumData.nextToken( );
hours = sumData.nextToken( );
hasMoreTokens( )
• Returns true if there are more data for nextToken to fetch
• import.util.*; // whenever StringTokenizer class to be used
String conversions
• Primitive types: int, double, boolean, character may be used
• int n = 123;
• String s = Integer.toString (n); // s becomes “123”
• double d = 12.34;
• String s = Double.toString (d); // s becomes “12.34”
parseInt
• n = Integer(SomeTextField.getText( ));– Converts a String into an int– d = Double.parseDouble (s);
String parameters
• String any = “Hello”; …
• return any + any– Method returns concatenated String
HelloHello
• Example of String processing: String class has replace method – only handels a single character at a time. See method replace page 288. Replaces substring