G51PR1 Introduction to Programming I 2000-2001 University of Nottingham Unit 8 : Strings.

Slides:



Advertisements
Similar presentations
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Advertisements

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Strings in Java 1. strings in java are handled by two classes String &
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Strings.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
23-Jun-15 Strings, Etc. Part I: String s. 2 About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects,
Fundamental Programming Structures in Java: Strings.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
28-Jun-15 String and StringBuilder Part I: String.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
The java.lang Package chapter 8 Java Certification Study Group February 2, 1998 Seth Ladd.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Chapter 7: Characters, Strings, and the StringBuilder.
CHAPTER 9 Text Processing and More about Wrapper Classes Copyright © 2016 Pearson Education, Inc., Hoboken NJ.
String Handling StringBuffer class character class StringTokenizer class.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
Strings Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and.
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called.
CSC Programming I Lecture 9 September 11, 2002.
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
String class. Method concat Create string object –> String st1, st2; Input character to string object –> st1=br.readLine(); st2= br.readLine(); Use method.
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
17-Feb-16 String and StringBuilder Part I: String.
1 Unit-2 Arrays, Strings and Collections. 2 Arrays - Introduction An array is a group of contiguous or related data items that share a common name. Used.
Strings A string is a sequence of characters that is treated as a single value. Strings are objects. We have been using strings all along. For example,
The Methods and What You Need to Know for the AP Exam
String and StringBuffer classes
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
EKT 472: Object Oriented Programming
University of Central Florida COP 3330 Object Oriented Programming
Programming in Java Text Books :
String and String Buffers
String Handling in JAVA
Primitive Types Vs. Reference Types, Strings, Enumerations
Modern Programming Tools And Techniques-I Lecture 11: String Handling
String and StringBuilder
Chapter 7: Strings and Characters
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
String and StringBuilder
Strings A string is a sequence of characters that is treated as a single value. Strings are objects. We have been using strings all along. Every time.
String and StringBuilder
Java – String Handling.
Lecture 07 String Jaeki Song.
String and StringBuilder
Strings in Java.
Dr. Sampath Jayarathna Cal Poly Pomona
Object Oriented Programming
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings

Overview Strings and StringBuffer Intro The String Class Example : ReverseString Accessor Methods Strings - StringBuffers and the compiler Using String and Stringbuffers Creating : –String –StringBuffer Modifying StringBuffer objects –Inserting Characters –Setting Characters Converting –Objects to Strings –Strings to Objects The valueOf method String Concatenation using + String’s –Constructors –Methods

Strings This section illustrates how to manipulate character data using the String and StringBuffer classes. It also teaches you about accessor methods and how the compiler uses Strings and StringBuffers behind the scenes. Why Two String Classes? The Java Dev. Env. provides two classes that store and manipulate character data: – String, for constant strings, and – StringBuffer, for strings that can change. To creating Strings and StringBuffers : Same way for creating an object of any type. E.g. StringBuffer dest = new StringBuffer( len );

The String Class A character string in Java is an object, defined by the String class String name = new String (“Hello World"); Because strings are so common, Java includes them in its syntax: String name = "Ken Arnold"; Java strings are immutable ; once a string object has a value, it cannot be changed String

The String Class A character in a string can be referred to by its position, or index The index of the first character is zero The String class is defined in the java.lang package (and is implicitly imported by default) Many helpful methods are defined in the String class such as : length() equals(String) startsWith(String) toUpperCase() toLowerCase() indexOf(String) subString(int begin) subString(int begin, int end) charAt(int index)

Example : ReverseString The reverseIt method accepts an argument of type String called source that contains the String data to be reversed. The method creates a StringBuffer, dest, the same size as source. It then loops backwards over all the characters in source and appends them to dest, thereby reversing the String. Finally, the method converts dest, a StringBuffer, to a String.

Example : ReverseString public class ReverseString { public static String reverseIt( String source ) { int len = source.length(); StringBuffer dest = new StringBuffer( len ); for ( int i = len - 1; i >= 0; i-- ) { dest.append( source.charAt( i ) ); } return dest.toString(); } // end method reverseIt } // end ReverseString

Accessor Methods The reverseIt method uses two accessor methods to obtain information about the source string: charAt and length. The reverseIt method uses StringBuffer's append method to add characters to dest. In addition to append, StringBuffer provides methods to insert characters into the buffer, modify a character at a specific location within the buffer, and so on. reverseIt converts the resulting StringBuffer to a String and returns the string. You can convert several different data types to Strings using String's valueOf method. You can also use methods from the Integer, Float, Double, and Long classes to convert the contents of a String to a number.

Accessor Methods As we know, an object's instance variables are encapsulated within the object, hidden inside, safe from inspection or manipulation by other objects. With certain well-defined exceptions, the object's methods are the only means by which other objects can inspect or alter an object's instance variables. The reverseIt method uses two of String's accessor methods to obtain information about the source string. class ReverseString { public static String reverseIt( String source ) { int i, len = source.length(); StringBuffer dest = new StringBuffer( len ); for ( i = ( len - 1 ); i >= 0; i-- ) { dest.append( source.charAt( i ) ); } return dest.toString(); }

Accessor Methods First, reverseIt uses String's length accessor method to obtain the length of the String source. int len = source.length(); Note that reverseIt doesn't care if String maintains its length attribute as an integer, as a floating point number, or even if String computes its length on the fly. reverseIt simply relies on the public interface of the length method, which returns the length of the String as an integer. That's all reverseIt needs to know. Second, reverseIt uses the charAt accessor, which returns the character at the position specified in the parameter i ( source.charAt( i )) The character returned by charAt is then appended to the StringBuffer dest. Since the loop variable i begins at the end of source and proceeds backwards over the string, the characters are appended in reverse order to the StringBuffer, thereby reversing the string.

Accessor Methods for String objects In addition to length and charAt, String supports a number of other accessor methods that provide access to substrings and the indices of specific characters in the String. public class StringExample { public static void main(String[] argv) { String str = new String("my name is Thanassis"); System.out.println("The string contains:" + str ); System.out.println("its length is :" + str.length() + " characters"); System.out.println("uppercase :" + str.toUpperCase()); System.out.println("lowercase :" + str.toLowerCase()); System.out.println("-is- starts at :" + str.indexOf("is") ); if (!str.equals("my name is Thanasis")) System.out.println("not true"); } The string contains:my name is Thanassis its length is :20 characters uppercase :MY NAME IS THANASSIS lowercase :my name is thanassis -is- starts at :8 not true

Strings and the Java Compiler The Java compiler uses Strings and StringBuffers behind the scenes to handle literal strings and concatenation. String and StringBuffer provide several other useful ways to manipulate string data, including concatenation, comparison, substitution, and conversion to upper and lower case. java.lang.String and java.lang.StringBuffer summarise and list all of the methods and variables supported by these two classes.

Using Strings vs Using StringBuffers You use Strings when you don't want the value of the String to change. For example, if you write a method that requires String data and the method is not going to modify the string in any way, use a String object. Typically, you'll want to use Strings to pass character data into methods and return character data from methods. The reverseIt method takes a String argument and returns a String value. The StringBuffer class provides for strings that will be modified; you use StringBuffers when you know that the value of the character data will change. You typically use StringBuffers for constructing character data, as in the reverseIt method. Because they are constants, Strings are typically cheaper than StringBuffers and they can be shared. So it's important to use Strings when they're appropriate.

Creating StringBuffers The bold line in the reverseIt method creates a StringBuffer named dest whose initial length is the same as source. class ReverseString { public static String reverseIt( String source ) { int i, len = source.length(); StringBuffer dest = new StringBuffer( len ); for ( i = ( len - 1 ); i >= 0; i-- ) { dest.append( source.charAt( i ) ); } return dest.toString(); } The code StringBuffer dest declares to the compiler that dest will be used to refer to an object whose type is StringBuffer, the new operator allocates memory for a new object, and StringBuffer( len ) initialises the object. These three steps - declaration, instantiation, and initialisation are - described in Creating Objects.

Modifying StringBuffers The reverseIt method uses StringBuffer's append method to add a character to the end of the destination string: dest. class ReverseString { public static String reverseIt( String source ) { int i, len = source.length(); StringBuffer dest = new StringBuffer( len ); for ( i = ( len - 1 ); i >= 0; i-- ) { dest.append( source.charAt( i ) ); } return dest.toString(); }

Modifying StringBuffers If the appended character causes the size of the StringBuffer to grow beyond its current capacity, the StringBuffer allocates more memory. Because memory allocation is a relatively expensive operation, you can make your code more efficient by initialising a StringBuffer's capacity to a reasonable first guess, thereby minimising the number of times memory must be allocated for it. For example, the reverseIt method constructs the StringBuffer with an initial capacity equal to the length of the source string, ensuring only one memory allocation for dest. The version of the append method used in reverseIt is only one of the StringBuffer methods that appends data to the end of a StringBuffer. There are several append methods that append data of various types, such as float, int, boolean, and even Object, to the end of the StringBuffer. The data is converted to a string before the append operation takes place.

Inserting Characters At times, you may want to insert data into the middle of a StringBuffer. You do this with one of StringBufffer's insert methods. This example illustrates how you would insert a string into a StringBuffer: StringBuffer sb = new StringBuffer( "Drink Java!" ); sb.insert( 6, "Hot " ); System.out.println( sb.toString() ); This code extract prints: Drink Hot Java! With StringBuffer's many insert methods, you specify the index before which you want the data inserted. In this example, "Hot " needed to be inserted before the 'J' in "Java". Indices begin at 0, so the index for 'J' is 6. To insert data at the beginning of a StringBuffer, use an index of 0. To add data at the end of a StringBuffer, use an index equal to the current length of the StringBuffer or use append.

Setting Characters Another useful StringBuffer modifier is setCharAt, which replaces the character at a specific location in the StringBuffer with the character specified in the argument list.. setCharAt is useful when you want to reuse a StringBuffer.

Converting Objects to Strings Using the toString() method : It's often convenient or necessary to convert an object to a String because you need to pass it to a method that accepts only String values. The reverseIt method used earlier in this lesson uses StringBuffer's toString method to convert the StringBuffer to a String object before returning the String. class ReverseString { public static String reverseIt( String source ) { int i, len = source.length(); StringBuffer dest = new StringBuffer( len ); for ( i = ( len - 1 ); i >= 0; i-- ) { dest.append( source.charAt( i ) ); } return dest.toString(); }

Converting Objects to Strings All classes inherit toString from the Object class and many classes in the java.lang package override this method to provide an implementation that is meaningful to that class. For example, the "type wrapper" classes - Character, Integer, Boolean etc- all override toString() and provide a String representation of the object.

The valueOf Method As a convenience, the String class provides the class method valueOf(), You can use valueOf() to convert variables of different types to Strings. For example, to print x and y next to each other (I.e. 56) : int x = 5; int y = 6; System.out.println( String.valueOf( x ) + y ); // prints 56 // compare with : System.out.println( x + y ); // prints 11 // and : System.out.println( x + “” + y ); // prints 56

Converting Strings to Numbers The String class itself does not provide any methods for converting a String to a floating point, integer, or other numerical type. However, four of the "type wrapper" classes ( Integer, Double, Float, and Long ) provide a class method named valueOf that converts a String to a that an object of that type. Here's a small example of the Float class's valueOf : String piStr = " "; float pi = Float.valueOf( piStr ); int i = Integer.parseInt( piStr ); trim()!

Concatenation and the + Operator In Java, you can use + to concatenate Strings together: String cat = "cat"; System.out.println( "con" + cat + "enation" ); This is a little deceptive because, as you know, Strings can't be changed. However, behind the scenes the compiler uses StringBuffers to implement concatenation. The above example compiles to: String cat = "cat"; System.out.println( new StringBuffer().append( "con" ).append( cat ).append( "enation" ) ); You can also use the + operator to append values to a String that are not themselves Strings: System.out.println( "Java's Number " + 1 ); The compiler converts the non-String value ( the integer 1 in the example ) to a String object before performing the concatenation operation.

Class java.lang.String public final class String extends Object implements Serializable The String class represents Character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example: String str = "abc"; is equivalent to: char data[ ] = {'a', 'b', 'c'}; String str = new String( data ); Here are some more examples of how strings can be used: System.out.println( "abc" ); String cde = "cde"; System.out.println( "abc" + cde ); String c = "abc".substring( 2,3 ); String d = cde.substring( 1, 2 );

String’s Constructors String(): Allocates a new String containing no characters. String(byte[ ]): Construct a new String by converting the specified array of bytes using the platform's default character encoding. String(byte[], int): Allocates a new String containing characters constructed from an array of 8-bit integer values. Deprecated. String(byte[], int, int): Construct a new String by converting the specified subarray of bytes using the platform's default character encoding.

String’s Constructors String( byte[ ], int, int, String ) : Construct a new String by converting the specified subarray of bytes using the specified character encoding. String( byte[ ], String ): Construct a new String by converting the specified array of bytes using the specified character encoding. String( char[ ] ) : Allocates a new String so that it represents the sequence of characters currently contained in the character array argument. String( char[ ], int, int ) : Allocates a new String that contains characters from a subarray of the character array argument. String( String ): Allocates a new string that contains the same sequence of characters as the string argument. String( StringBuffer ): Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.

String’s Methods charAt( int ): Returns the character at the specified index. compareTo( String ): Compares two strings lexicographically. concat( String ) : Concatenates the specified string to the end of this string. copyValueOf(char[]) : Returns a String using the specified character array. copyValueOf(char[],int,int ): Returns a String that is equivalent to the specified character array. endsWith( String ) : Tests if this string ends with the specified suffix. equals( Object ) : Compares this string to the specified object. equalsIgnoreCase(String) : Compares this String to another object. getBytes() : Convert this String into bytes according to the platform's default character encoding, storing the result into a new byte array. getBytes( int, int, byte[ ], int ) : Copies characters from this string into the destination byte array. Deprecated. getBytes( String ) : Convert this String into bytes according to the specified character encoding, storing the result into a new byte array.

String’s Methods getChars( int, int, char[ ], int ) : Copies characters from this string into the destination character array. hashCode() : Returns a hashcode for this string. indexOf( int ) : Returns the index within this string of the first occurrence of the specified character. indexOf( int, int ) : Returns the index within this string of the first occurrence of the specified character, starting the search at index. indexOf( String ) : Returns the index within this string of the first occurrence of t he specified substring. indexOf( String, int ) : Returns the index within this string of the first occurrence of the specified substring, starting at index. intern() : Returns a canonical representation for the string object. lastIndexOf( int ) : Returns the index within this string of the last occurrence of the specified character. lastIndexOf( int, int ) : Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

String’s Methods lastIndexOf( String ) : Returns the index within this string of the rightmost occurrence of the specified substring. lastIndexOf( String, int ) : Returns the index within this string of the last occurrence of the specified substring. length() : Returns the length of this string. regionMatches( boolean, int, String, int, int ) : Tests if two string regions are equal. regionMatches( int, String, int, int ) : Tests if two string regions are equal. replace( char, char ) : Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. startsWith( String ) : Tests if this string starts with the specified prefix. startsWith( String, int ): Tests if this string starts with the specified prefix. substring( int ) : Returns a new string that is a substring of this string. substring( int, int ) : Returns a new string that is a substring of this string. toCharArray() : Converts this string to a new character array. toLowerCase() : Converts this String to lowercase.

String’s Methods toLowerCase(Locale) : Converts all of the characters in this String to lower case using the rules of the given locale. toString() : This object ( which is already a string! ) is itself returned. toUpperCase() : Converts this string to uppercase. toUpperCase(Locale ): Converts all of the characters in this String to upper case using the rules of the given locale. trim() : Removes white space from both ends of this string. valueOf( boolean ) : Returns the string representation of the boolean argument. valueOf( char ) : Returns the string representation of the char * argument. valueOf( char[ ] ) : Returns the string representation of the char array argument. valueOf( char[ ], int, int ) : Returns the string representation of a specific subarray of the char array argument. valueOf( double ) : Returns the string representation of the double argument. valueOf( float ) : Returns the string representation of the float argument. valueOf( int ) : Returns the string representation of the int argument. valueOf( long ) : Returns the string representation of the long argument. valueOf( Object ) : Returns the string representation of the Object argument.

Summary Strings and StringBuffer Intro The String Class Example : ReverseString Accessor Methods Strings - StringBuffers and the compiler Using String and Stringbuffers Creating : –String –StringBuffer Modifying StringBuffer objects –Inserting Characters –Setting Characters Converting –Objects to Strings –Strings to Objects The valueOf method String Concatenation using + String’s –Constructors –Methods