Presentation is loading. Please wait.

Presentation is loading. Please wait.

Strings Chapter 7 CSCI 1302. CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.

Similar presentations


Presentation on theme: "Strings Chapter 7 CSCI 1302. CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String."— Presentation transcript:

1 Strings Chapter 7 CSCI 1302

2 CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String Length and Individual Characters –String Concatenation –Extracting Substrings –String Comparisons –String Conversions

3 CSCI 1302 – Strings3 Outline –Finding a Character or a Substring –Conversions between Strings and Arrays –Converting Characters and Numeric Values to Strings The Character Class The StringBuffer Class –Constructing a String Buffer –Modifying Strings in the Buffer –Important Methods

4 CSCI 1302 – Strings4 Outline The StringTokenizer class The Scanner class (JDK 1.5 feature) Implementing MyInput Using Scanner Command-Line Arguments –Passing Strings to the main Method –Processing Command-Line Arguments

5 CSCI 1302 – Strings5 Introduction Sequence of characters Often represented as an array of characters Is an object in Java String – efficient for storing and processing StringBuffer – used for flexible strings that can be modified StringTokenizer – utility class

6 CSCI 1302 – Strings6 The String class Models a sequence of characters Total of eleven constructors Over forty methods for working with strings Methods include examining individual characters in a sequence, comparing strings, searching substrings, extracting substrings, and creating a copy of a string with a change of case

7 CSCI 1302 – Strings7 Constructing String s Strings can be created from a string literal or an array of characters String newString = new String(“Message”); Shorthand initializer String newString = “Message”; Array of characters char[] charArray = {‘H’,’i’,’!’}; String newString = new String(charArray);

8 CSCI 1302 – Strings8 Immutable Strings A String object is immutable, its contents cannot be changed String s = “Java”; s = “HTML”;

9 CSCI 1302 – Strings9 Canonical Strings JVM stores two String objects in the same object if they were created with the same string literal using shorthand initialization This is a canonical string Use the intern() method to return the canonical string

10 CSCI 1302 – Strings10 Canonical Strings s1 == s is false s2 == s is true s == s3 is true

11 CSCI 1302 – Strings11 String Length Use length() to get length of a string String message = “Java”; message.length(); // returns 4

12 CSCI 1302 – Strings12 Individual Characters Use charAt(index) to retrieve a specific character Index starts at 0 Don’t use array index notation message[2]

13 CSCI 1302 – Strings13 String Concatenation Use the concat(String s) method or the + symbol to concatenate two strings String s1 = “Hello ”; String s2 = “World”; String s3 = s1.concat(s2); String s3 = s1 + s2; Hello World

14 CSCI 1302 – Strings14 Extracting Substrings Returns a substring of the original string public String substring(int begin, int end); public String substring(int begin);

15 CSCI 1302 – Strings15 String Comparisons Compare string contents with the equals(String s) method not == String s0 = “ Java”; String s1 = “Welcome to” + s0; String s2 = Welcome to Java”; System.out.println(“s1==s2 is “ + (s1==s2)); // false System.out.println(“s1.equals(s2) is “ + (s1.equals(s2))); // true

16 CSCI 1302 – Strings16 String Comparisons Can also use the compareTo(String s) method Don’t use >, >=, <, or <= s1 = “abc”; s2 = “abg”; s3 = “abc”; s4 = “aba”; s1.compareTo(s2); // returns -4 s1.compareTo(s3); // returns 0 s1.compareTo(s4); // returns 2

17 CSCI 1302 – Strings17 String Comparisons Use equalsIgnoreCase(String s) for case- insensitive equality Use the regionMatches method for comparing substrings Use startsWith(prefix) or endsWith(suffix) to check whether a string starts or ends with a certain substring

18 CSCI 1302 – Strings18 String Conversions String contents cannot be changed, but new strings can be created and transformed with various methods “Welcome”.toLowerCase(); // welcome “Welcome”.toUpperCase(); // WELCOME “ Welcome ”.trim(); // Welcome “Welcome”.replace(‘e’,’A’); // WAlcomA “Welcome”.replaceFirst(“e”,”A”); // WAlcome “Welcome”.replaceAll(“e”,”A”) // WAlcomA

19 CSCI 1302 – Strings19 String Conversions Use these methods to find the first or last (add last in front of each method name) occurrence of a character or substring in a given string All return -1 if it is not found public int indexOf(int ch); public int indexOf(int ch, int from); public int indexOf(String str); public int indexOf(String str, int fromIndex);

20 CSCI 1302 – Strings20 String Conversions Examples "Welcome to Java".indexOf('W') returns 0 "Welcome to Java".indexOf('x') returns -1 "Welcome to Java".indexOf('o', 5) returns 9 "Welcome to Java".indexOf("come") returns 3 "Welcome to Java".indexOf("Java", 5) returns 11 "Welcome to Java".indexOf("java", 5) returns -1 "Welcome to Java".lastIndexOf('a') returns 14

21 CSCI 1302 – Strings21 Conversions between Strings and Arrays String to char Array char[] chars = “Java”.toCharArray(); Use getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) to replace substrings char[] dst = {‘J’,’A’,’V’,’A’}; “SAWS”.getChars(2,3,dst,2); dst becomes {‘J’,’A’,’W’,’S’}

22 CSCI 1302 – Strings22 Conversions between Strings and Arrays Convert array of characters into a string String str = new String(new char[]{‘J’,’a’,’v’,’a’}); String str = String.valueOf(new char[]{‘J’,’a’,’v’,’a’});

23 CSCI 1302 – Strings23 Conversions between Strings and Arrays Convert other types to strings Use overloaded versions of valueOf to convert char, double, long, int, and float. String str = new String.valueOf(5.44); String str = String.valueOf(3);

24 CSCI 1302 – Strings24 Palindromes A word that is the same backwards and forwards Examples of palindromes: –Mom –Noon –Dad –Kayak –Racecar See TestPalindrome.java

25 CSCI 1302 – Strings25 Primitive wrapper classes Java provides wrapper classes for the primitive types so they can be treated like objects All contained in the java.lang package Helps process primitive values Will go into more detail with other primitive wrapper classes in Chapter 9

26 CSCI 1302 – Strings26 The Character class One constructor, more than 30 methods Most methods are static Create a Character object Character character = new Character(‘a’); Return a Character object charValue(‘a’); Compare Character objects character.compareTo(‘a’); character.equals(‘a’);

27 CSCI 1302 – Strings27 The StringBuffer class More flexible than String Can add, insert, or append new contents Three constructors, over thirty methods See Figure 7.8 on p.270 for common methods

28 CSCI 1302 – Strings28 Constructing StringBuffer Three constructors – public StringBuffer() – No characters, initial capacity of sixteen characters – public StringBuffer(int length) – No characters, initial capacity of length characters – public StringBuffer(String s) – Constructs a string buffer with an initial capacity of sixteen plus the length of the string argument

29 CSCI 1302 – Strings29 Modifying StringBuffers Can append new contents to the end of an existing buffer, insert new contents, or delete/replace characters Append characters StringBuffer sb = new StringBuffer(“We”); sb.append(“lcome to Java”); Insert characters StringBuffer sb = new StringBuffer(“As”); sb.insert(1,“ Welcome to Java”); A Welcome to Javas

30 CSCI 1302 – Strings30 Modifying StringBuffers Other useful methods sb.delete(8, 11); // Welcome Java sb.deleteCharAt(8); // Welcome o Java sb.reverse() // avaJ ot emocleW sb.replace(11,15,”HTML”); // Welcome to HTML sb.setCharAt(0,’w’); // welcome to Java

31 CSCI 1302 – Strings31 Modifying StringBuffers Other useful methods – toString() – returns the string – capacity() – returns the capacity – length() – returns the number of characters stored – setLength(newLength) – sets the length, truncates or pads – charAt(index) – returns the character at specified index (0-based) See PalindromeIgnoreNonAlphanumeric.java

32 CSCI 1302 – Strings32 The StringTokenizer class Allows you to process strings Specify a set of delimiters Each string “piece” is a token Specify delimiters in constructors

33 CSCI 1302 – Strings33 Constructing StringTokenizers public StringTokenizer(String s, String delim, boolean returnDelims); – delimiters are counted as tokens public StringTokenizer(String s, String delim); – delimiters are not counted as tokens public StringTokenizer(String s); – default delimiters (“ \t\n\r”) are not counted as tokens

34 CSCI 1302 – Strings34 Using StringTokenizers countTokens() – Return the number of tokens in string hasMoreTokens() – Tells whether the string has more tokens or not nextToken() – return next token

35 CSCI 1302 – Strings35 The Scanner class Can use words as the delimiter Should be used when words, not single characters or several single characters are delimiters Can parse primitive types See TestScanner.java

36 CSCI 1302 – Strings36 Command Line Arguments Pass arguments on the command line to main methods Separated by spaces, strings with spaces must be enclosed in double quotes Stored in the args array See Calculator.java

37 CSCI 1302 – Strings37 Review http://cs.armstrong.edu/liang/intro5e.html


Download ppt "Strings Chapter 7 CSCI 1302. CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String."

Similar presentations


Ads by Google