Java Programming Strings Chapter 7.

Slides:



Advertisements
Similar presentations
Java
Advertisements

Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
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.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text I/O.
©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.
Fundamental Programming Structures in Java: Strings.
The String Class. Objectives: Learn about literal strings Learn about String constructors Learn about commonly used methods Understand immutability of.
©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.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapters 3-4: Using Objects.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 8 Strings 1.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Strings Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts.
Chapter 7: Characters, Strings, and the StringBuilder.
CHAPTER 9 Text Processing and More about Wrapper Classes Copyright © 2016 Pearson Education, Inc., Hoboken NJ.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
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.
1 The String Class F Constructing a String: F Obtaining String length and Retrieving Individual Characters in a string F String Concatenation (concat)
Strings Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and.
String Definition A String is a set of characters that behaves as a single unit. The characters in a String include upper-case and lower-case letters,
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
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.
Strings and ArrayLists April 23, 2012 ASFA AP CS.
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
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:
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,
String and StringBuffer classes
The String Class.
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Strings.
EKT 472: Object Oriented Programming
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
Chapter 7: Strings and Characters
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
Part a: Fundamentals & Class String
Chapter 9 Strings and Text I/O
Java – String Handling.
Chapter 9 Strings.
Lecture 07 String Jaeki Song.
CS2011 Introduction to Programming I Strings
Chapter 10 Thinking in Objects Part 2
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:

Java Programming Strings Chapter 7

String Class An object of the String class represents a string of characters. The String class belongs to the java.lang package, which does not require an import statement. Like other classes, String has constructors and methods.

Strings string: An object storing a sequence of text characters. Two ways to create a string As a new object through the String class String name = new String("text"); Convenient shorthand method String name = "text";

Immutability immutable. String name = "text"; Once created in memory, a string cannot be changed: none of its methods changes the string If a string variable is reassigned, the memory address is deleted and a new memory address is created Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change.

Advantages Of Immutability Uses less memory. String word1 = "Java"; String word2 = word1; String word1 = “Java"; String word2 = new String(word1); word1 "Java" word1 "Java" word2 "Java" word2 Less efficient: wastes memory OK

Disadvantages of Immutability Less efficient — you need to create a new string and throw away the old one even for small changes. String word = "java"; word = "HTML"; word "java" "HTML"

Manipulating Characters Character class Contains standard methods for testing values of characters Methods that begin with “is” Such as isUpperCase() Return Boolean value Can be used in comparison statements Methods that begin with “to” Such as toUpperCase() Return character that has been converted to stated format

Indexes Characters of a string are numbered with 0-based indexes: String name = "Java fun"; First character's index : 0 Last character's index : 1 less than the string's length The individual characters are values of type char index 1 2 3 4 5 6 7 character J a v f u n

String Methods These methods are called using the dot notation: Method name Description indexOf(str) index where the start of the given string appears in this string (-1 if not found) length() number of characters in this string substring(index1, index2) or substring(index1) the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 is omitted, grabs till end of string toLowerCase() a new string with all lowercase letters toUpperCase() a new string with all uppercase letters charAt(index) Returns the character at the specified index These methods are called using the dot notation: String name = "Hello World"; System.out.println(name.length());

Length of a String It is sometimes useful to determine the length of a string Use the length( ) methods String s = "Java is Fun"; int sLength = s.length(); System.out.println(sLength); // 11 The method counts the number of characters in the string variable. It produces an integer result.

Modifying String Java is case sensitive String s1 = "Java"; String s2 = "java"; s1 and s2 represent two different strings To get around this possible obstacle, Java has methods that display a string in all upper case letters or all lower case letters toUpperCase( ) toLowerCase( )

Modifying String These methods build and return a new string, rather than modifying the current string. To modify a variable's value, you must reassign it: String s = "Hello World"; s1 = s.toUpperCase(); s2 = s.toLowerCase(); System.out.println(s1 + " " + s2); // HELLO WORLD hello world

Looking for a String Another common task when handling strings is to see whether one string can be found inside another. This is useful when you are looking for a specific text inside a large string (such as a document) To look inside a string, use indexOf( string ) If string is found, an integer that represents the starting position of the first occurrence is returned If string is not found, -1 is returned lastIndexOf( string ) Returns the position of the last occurrence String s = "Java is fun"; int sfind = s.indexOf("fun"); System.out.println(sfind); // 8

Looking for a String // index 012345678901234567890123456 String name = "President George Washington"; name.indexOf ('P'); 0 name.indexOf ('e'); 2 name.indexOf ("George"); 10 name.indexOf ('e', 3); 6 name.indexOf ("Bob"); -1 name.lastIndexOf ('e'); 15 Returns: (starts searching at position 3) String has four overloaded versions of indexOf and four versions of lastIndexOf. lastIndexOf(ch, fromPos) starts looking at fromPos and goes backward towards the beginning of the string. (not found)

Replacing Part of a String We may also want to find and replace parts of a large string There are a few replace methods available replace(oldString, newString) replaceFirst(oldString, newString) replaceAll(oldString, newString) String s = "Java is fan"; s1 = s.replace("fan","fun"); System.out.println(s1); // Java is fun

String methods // index 01234567890 String s1 = "Hello World"; System.out.println(s1.length()); System.out.println(s1.indexOf("r")); System.out.println(s1.charAt(1)); System.out.println(s1.substring(3, 7)); String s2 = s1.substring(0, 5); System.out.println(s2.toLowerCase()); 11 8 e lo W hello

Comparing Strings One thing we will be testing often in our programs is whether one string is the same as the other Two basic commands: equals( ) compareTo( ) Do not compare two Strings using the == operator Not comparing values Comparing computer memory locations

Comparing Strings equals() method equalsIgnoreCase() method Evaluates contents of two String objects to determine if they are equivalent Returns true if objects have identical contents equalsIgnoreCase() method Ignores case when determining if two Strings equivalent Useful when users type responses to prompts in programs s1 = "Java"; s2 = "java"; boolean eq = s1.equals(s2); System.out.println(eq); // false

Comparing Strings compareTo() method Compares two Strings and returns: Zero Only if two Strings refer to same value Negative number If calling object “less than” argument Positive number If calling object “more than” argument

Comparing Strings These methods return a boolean value (true or false) Description equals(str) whether two strings contain the same characters equalsIgnoreCase(str) whether two strings contain the same characters, ignoring upper vs. lower case startsWith(str) whether one contains other's characters at start endsWith(str) whether one contains other's characters at end contains(str) whether the given string is found within this one These methods return a boolean value (true or false)

String Concatenation Concatenation Join multiple variables together Two ways to concatenate concat method String s3 = s1.concat(s2); Convenient shorthand String s3 = s1 + s2; s1 = "Hello"; s2 = "World"; s3 = s1 + " " + s2;

Numbers to Strings Three ways to convert a number into a string: 1. String s = "" + num; 2. String s = Integer.toString (i); String s = Double.toString (d); 3. String s = String.valueOf (num); Integer and Double are “wrapper” classes from java.lang that represent numbers as objects. They also provide useful static methods. s = "" + 123; //"123" You can also convert a char to a string by using String s = "" + ch; or String s = ch + ""; By convention, a static method valueOf in a class converts something (its arguments) into an object of this class. For example: public class Fraction { public static Fraction valueOf(double x) {...} should take a double and return a corresponding Fraction. Here String.valueOf(x) returns a string. s = Integer.toString(123); //"123" s = Double.toString(3.14); //"3.14" s = String.valueOf(123); //"123"

Strings to Numbers Integer and Double class Automatically imported into programs (java.lang) Convert String to integer valueOf() method Convert String to Integer class object intValue() method Extract simple integer from wrapper class parseInt() method Returns its integer value Convert String to double parseDouble() method Returns its double value

StringBuilder The StringBuilder/StringBuffer class is an alternative to the String class. Can be used wherever a string is used. More flexible than String. You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created.

StringBuilder Using StringBuilder objects StringBuilder constructors Provides improved computer performance over String objects Can insert or append new contents into StringBuilder StringBuilder constructors public StringBuilder () public StringBuilder (int capacity) public StringBuilder (String s) StringBuilder name = new StringBuilder("Hello");

StringBuilder Method Description append(str) Adds a string to the end of the StringBuilder object delete(start, end) Deletes characters at the specified index insert(index, str) Inserts string into the builder at the position offset replace(start, end, str) Replaces the characters in this builder at the specified index with the specified string setCharAt(index, char) Changes a character at the specified index CharAt(index) Returns character at the specified index

Finding Palindromes Write a program to check whether a string is a palindrome: a string that reads the same forward and backward. civic radar level rotor kayak reviver racecar redder

Finding Palindromes import java.util.Scanner; public class CheckPalindrome { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a string: "); String s = input.nextLine(); if (isPalindrome(s)) System.out.println(s + " is a palindrome"); else System.out.println(s + " is not a palindrome"); } // continued on next page

Finding Palindromes public static boolean isPalindrome(String s) { // Set index of the first and last characters in the string int low = 0; int high = s.length() - 1; while (low < high) { if (s.charAt(low) != s.charAt(high)) return false; // Not a palindrome low++; high--; } return true; // The string is a palindrome