String and StringBuilder

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.
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 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.
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.
Programming 2 CS112- Lab 2 Java
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.
Lab session 3 and 4 Topics to be covered Escape sequences Escape sequences Variables /identifiers Variables /identifiers Constants Constants assignment.
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 ,
Strings Edward J. Biebel. Strings Strings are fundamental part of all computing languages. At the basic level, they are just a data structure that can.
Strings.
String Class. Objectives and Goals Identify 2 types of Strings: Literal & Symbolic. Learn about String constructors and commonly used methods Learn several.
Strings Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts.
Chapter 7: Characters, Strings, and the StringBuilder.
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.
String String Builder. System.String string is the alias for System.String A string is an object of class string in the System namespace representing.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
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.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
2 Arrays Array is a data structure that represents a collection of the same type of data. A "fixed length list".
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
The String class is defined in the java.lang package
String and StringBuffer classes
Strings and Text Processing
The String Class.
String and Lists Dr. José M. Reyes Álamo.
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
String class.
EKT 472: Object Oriented Programming
University of Central Florida COP 3330 Object Oriented Programming
Programming in Java Text Books :
String and String Buffers
String String Builder.
String Handling in JAVA
Primitive Types Vs. Reference Types, Strings, Enumerations
String class in java Visit for more Learning Resources string.
String Objects & its Methods
String and StringBuilder
Chapter 7: Strings and Characters
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
String and StringBuilder
String and Lists Dr. José M. Reyes Álamo.
Java – String Handling.
16 Strings.
Lecture 07 String Jaeki Song.
String and StringBuilder
String methods 26-Apr-19.
Strings in Java.
Dr. Sampath Jayarathna Cal Poly Pomona
Object Oriented Programming
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

String and StringBuilder Part I: String 27-Nov-18

About Strings Strings are objects, but there is a special syntax for writing String literals: "Hello" Strings, unlike most other objects, have a defined operation (as opposed to a method): " This " + "is String " + "concatenation"" Strings can contain any character, but some of them must be “escaped” in order to write them in a literal \" stands for the double-quote (") character \n stands for the newline character \\ stands for the backslash (\)character Each of these is written as a two-character sequence, but represents a single character in the string

Useful String methods I char charAt(int index) Returns the character at the given index position (0-based) boolean startsWith(String prefix) Tests if this String starts with the prefix String boolean endsWith(String suffix) Tests if this String ends with the suffix String

Useful String methods II boolean equals(Object obj) Tests if this String is the same as the obj (which may be any type; false if it’s not a String) boolean equalsIgnoreCase(String other) Tests if this String is equal to the other String, where case does not matter int length() Returns the length of this string; note that this is a method, not an instance variable

Useful String methods III int indexOf(char ch) Returns the position of the first occurrence of ch in this String, or -1 if it does not occur int indexOf(char ch, int fromIndex) Returns the position of the first occurrence of ch, starting at (not after) the position fromIndex There are two similar methods that take a String instead of a char as their first argument

Useful String methods IV int lastIndexOf(char ch) Returns the position of the last occurrence of ch in this String, or -1 if it does not occur int lastIndexOf(char ch, int fromIndex) Returns the position of the last occurrence of ch, searching backward starting at position fromIndex There are two similar methods that take a String instead of a char as their first argument

Useful String methods V String substring(int beginIndex) Returns a new string that is a substring of this string, beginning with the character at the specified index and extending to the end of this string. String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string, beginning at the specified beginIndex and extending to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex

Understanding “index” With charAt(index), indexOf(x), and lastIndexOf(x), just count characters (starting from zero) "She said, \"Hi\"" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 With substring(from) and substring(from, to), it works better to count positions between characters "She said, \"Hi\"" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 So, for example, substring(4, 8) is "said", and substring(8, 12) is ", \"H" If indexOf(',') is 8, then substring(0, indexOf(',')) is "She said" and substring(indexOf(',') + 1) is " \"Hi\""

Useful String methods VI String toUpperCase() Returns a new String similar to this String, in which all letters are uppercase String toLowerCase() Returns a new String similar to this String, in which all letters are lowercase String trim() Returns a new String similar to this String, but with whitespace removed from both ends

Useful String methods VII String[] split(String regex) Breaks the string up into an array of strings The parameter is a regular expression that defines what separates the strings For example, String s = "one, two, three"; String[] ss = s.split(", "); This assigns the array {"one", "two", "three"} to ss Regular expressions are complex expressions that assign meanings to many common punctuation marks, such as +, *, period, and [ Hence, regular expressions are powerful, but can be treacherous if you aren’t very familiar with them

Finally, a useless String method String toString() Returns this String Why do we have this method? Consistency--Every Object has a toString() method

Strings are immutable A String, once created, cannot be changed None of the preceding methods modify the String, although several create a new String Statements like this create new Strings: myString = myString + anotherCharacter; Creating a few extra Strings in a program is no big deal Creating a lot of Strings can be very costly

More about equals If you write String s = "abc"; String t = "abc"; the compiler only creates the string "abc" once, and makes s and t both refer to this one string It can do this because strings are immutable Hence, the test s == t will be true However, if you now write String u = "a" + "bc"; the test s == u will be false This is because they are different strings Moral: Use equals for strings, not ==

Still more about equals Suppose you want to test whether a variable name has the value "Dave" Here’s the obvious way to do it: if (name.equals("Dave")) { ... } But you could also do it this way: if ("Dave".equals(name)) { ... } It turns out that the second way is usually better Why? If name == null, the first way will cause a NullPointerException, but the second way will just return false

Part II: StringBuilder Strings, Etc. Part II: StringBuilder 27-Nov-18

About StringBuilders A StringBuilder has a capacity (the number of characters it can hold) and a length (the number of characters it is currently holding) If the capacity is exceeded, the StringBuilder is copied to a new location with more room StringBuilder is a reimplementation of StringBuffer The API (collection of methods) is the same StringBuffers are threadsafe, but StringBuilders are more efficient StringBuilders are used to implement String concatenation Whenever you say String s = "ab" + "cd", Java creates a StringBuffer containing the characters a and b, appends the characters c and d to it, and converts the result back to a String As you might guess, this isn’t terribly efficient, but it’s fine if you don’t overdo it

StringBuilder constructors Constructs a StringBuilder with a capacity of 16 characters StringBuilder(int capacity) Constructs a StringBuilder with the requested capacity StringBuilder(String str) Constructs a StringBuilder containing the String str

Useful StringBuilder methods I StringBuilder append(X) Appends X to the end of this StringBuilder; also (as a convenience) returns this StringBuilder The append method is so heavily overloaded that it will work with any argument; if the argument is an object, its toString() method is used

Useful StringBuilder methods II int length() Returns the number of characters in this StringBuilder void setLength(int newLength) Sets the number of characters in this StringBuilder; this may result in truncation of characters at the end, or addition of null characters

Useful StringBuilder methods III char charAt(int index) Returns the character at the location index void setCharAt(int index, char ch) Sets the character at location index to ch StringBuilder reverse() The sequence of characters in this StringBuilder is replaced by the reverse of this sequence, and also returned as the value of the method

Useful StringBuilder methods IV StringBuilder insert(int offset, X) Insert X starting at the location offset in this StringBuilder, and also return this StringBuilder as the value of the method. Like append, this method is heavily overloaded StringBuilder deleteCharAt(int index) Deletes the character at location index StringBuilder delete(int start, int end) Deletes chars at locations start through end-1

Useful StringBuilder methods V String substring(int start) Returns a new String of characters from this StringBuilder, beginning with the character at the specified index and extending to the end of this string. String substring(int start, int end) Returns a new String of characters from this StringBuilder, beginning at location start and extending to the character at index end-1. Thus the length of the substring is end-begin String toString() Returns the characters of this StringBuilder as a String

When to use StringBuilders If you make a lot (thousands) of changes or additions to a String, it is much more efficient to use a StringBuilder If you are simply examining the contents of a String, then a String is at least as efficient as a StringBuilder For incidental use (such as creating output lines), use Strings; they are more convenient

Strings, etc. Part III: Characters 27-Nov-18

The Character class char is a primitive type, not an object, therefore… …there are no methods you can call on a char This is why we need a Character class! There are a lot of methods in the Character class They are all static Do you see why?

Some Character methods static boolean isDigit(char ch) static boolean isLetter(char ch) static boolean isLetterOrDigit(char ch) static boolean isLowerCase(char ch) static boolean isUpperCase(char ch) static boolean isWhitespace(char ch) static char toLowerCase(char ch) static char toUpperCase(char ch) For more methods, see java.lang.Character

The End