+ All Categories
Home > Documents > Characters, Strings and the String Buffer Jim Burns.

Characters, Strings and the String Buffer Jim Burns.

Date post: 29-Dec-2015
Category:
Upload: osborne-scott
View: 228 times
Download: 1 times
Share this document with a friend
33
Characters, Strings Characters, Strings and the String and the String Buffer Buffer Jim Burns Jim Burns
Transcript
Page 1: Characters, Strings and the String Buffer Jim Burns.

Characters, Strings and the Characters, Strings and the String BufferString Buffer

Jim BurnsJim Burns

Page 2: Characters, Strings and the String Buffer Jim Burns.

Identifying problems that can occur Identifying problems that can occur when you manipulate string datawhen you manipulate string data

String is not a simple data type like int, String is not a simple data type like int, float, or doublefloat, or double

String creates an instance of a class, the String creates an instance of a class, the class class StringString

As such it contains a reference or an As such it contains a reference or an address and not the actual stringaddress and not the actual string

So you cannot do equality comparisons of So you cannot do equality comparisons of two different instances of String, because two different instances of String, because you are simply testing if the addresses are you are simply testing if the addresses are the samethe same

Page 3: Characters, Strings and the String Buffer Jim Burns.

An example of incorrect codeAn example of incorrect codeimport javax.swing.JOptionPane;import javax.swing.JOptionPane;public class TryToCompareStringspublic class TryToCompareStrings{{ public static void main(String[] args)public static void main(String[] args) {{ String aName = "Carmen";String aName = "Carmen"; String anotherName;String anotherName; anotherName = JOptionPane.showInputDialog(null,anotherName = JOptionPane.showInputDialog(null, "Enter your name");"Enter your name"); if(aName == anotherName)if(aName == anotherName) JOptionPane.showMessageDialog(null, aName +JOptionPane.showMessageDialog(null, aName + " equals " + anotherName);" equals " + anotherName); elseelse JOptionPane.showMessageDialog(null, aName +JOptionPane.showMessageDialog(null, aName + " does not equal " + anotherName);" does not equal " + anotherName); System.exit(0);System.exit(0); }} }}

Page 4: Characters, Strings and the String Buffer Jim Burns.

Correct CodeCorrect Code import javax.swing.JOptionPane;import javax.swing.JOptionPane; public class CompareStringspublic class CompareStrings {{ public static void main(String[] args)public static void main(String[] args) {{ String aName = "Carmen";String aName = "Carmen"; String anotherName;String anotherName; anotherName = JOptionPane.showInputDialog(null,anotherName = JOptionPane.showInputDialog(null, "Enter your name");"Enter your name"); if(aName.equals(anotherName))if(aName.equals(anotherName)) JOptionPane.showMessageDialog(null, aName +JOptionPane.showMessageDialog(null, aName + " equals " + anotherName);" equals " + anotherName); elseelse JOptionPane.showMessageDialog(null, aName +JOptionPane.showMessageDialog(null, aName + " does not equal " + anotherName);" does not equal " + anotherName); System.exit(0);System.exit(0); }} }}

Page 5: Characters, Strings and the String Buffer Jim Burns.

Three classes for working with Three classes for working with stringsstrings

CharacterCharacter—a class whose instances can hold a —a class whose instances can hold a single character value—provides methods that single character value—provides methods that can manipulate or inspect single-character datacan manipulate or inspect single-character data

StringString—a class for working with fixed-string data—a class for working with fixed-string data—that is unchanging data composed of multiple —that is unchanging data composed of multiple characters, strings that are characters, strings that are immutableimmutable

StringBufferStringBuffer—a class for storing and —a class for storing and manipulating changeable data composed of manipulating changeable data composed of mulltiple charactersmulltiple characters

Page 6: Characters, Strings and the String Buffer Jim Burns.

Manipulating CharactersManipulating CharactersWe know the char data type can hold any We know the char data type can hold any

single charactersingle characterCharacter class provides the following Character class provides the following

methodsmethods isUpperCase(), toUpperCase(), isUpperCase(), toUpperCase(),

isLowerCase(), toLowerCase(), isDigit(), isLowerCase(), toLowerCase(), isDigit(), isLetter(), isLetterOrDigit(), isWhitespace()isLetter(), isLetterOrDigit(), isWhitespace()

Methods that begin with ‘is…’ perform tests Methods that begin with ‘is…’ perform tests delivering true or false valuesdelivering true or false values

Methods that begin with ‘to…’ perform Methods that begin with ‘to…’ perform conversionsconversions

Page 7: Characters, Strings and the String Buffer Jim Burns.

Declaring a String ObjectDeclaring a String Object We know that characters enclosed within double We know that characters enclosed within double

quotation marks are literal stringsquotation marks are literal strings We’ve learned to print these strings using We’ve learned to print these strings using

println() and showMessageDialog()println() and showMessageDialog() An literal string is an unnamed object, or An literal string is an unnamed object, or

anonymous object, of the String classanonymous object, of the String class A String variable is simply a named object of the A String variable is simply a named object of the

same class.same class. The class String is defined in java.lang.String, which The class String is defined in java.lang.String, which

is automatically imported into every program you writeis automatically imported into every program you write

Page 8: Characters, Strings and the String Buffer Jim Burns.

Declaring a String variableDeclaring a String variable

When you declare a String variable, the When you declare a String variable, the String itself—that is, the series of String itself—that is, the series of characters contained in the String—is characters contained in the String—is distinct from the variable you use to refer distinct from the variable you use to refer to it.to it.

Can initialize a String variable with or Can initialize a String variable with or without a String constructorwithout a String constructor

Page 9: Characters, Strings and the String Buffer Jim Burns.

With or without a String ConstructorWith or without a String Constructor

With the constructorWith the constructor

String aGreeting = new String(“Hello”);String aGreeting = new String(“Hello”);

Without the constructorWithout the constructor

String aGreeting = “Hello”;String aGreeting = “Hello”;

Unlike other classes, you can create a String Unlike other classes, you can create a String object without using the keyword new or object without using the keyword new or explicitly calling the class constructorexplicitly calling the class constructor

Page 10: Characters, Strings and the String Buffer Jim Burns.

Comparing String ValuesComparing String ValuesConsider the following two statements:Consider the following two statements:

String aGreeting = “hello”;String aGreeting = “hello”;aGreeting = “Bonjour”;aGreeting = “Bonjour”;

These statements are syntactically correct. What These statements are syntactically correct. What happens is that the address contained in happens is that the address contained in aGreeting is changed to point to “Bonjour” rather aGreeting is changed to point to “Bonjour” rather than “hello”, both of which are contained at than “hello”, both of which are contained at different locations in memory. Eventually, the different locations in memory. Eventually, the garbage collector discards the “hello” garbage collector discards the “hello” characters.characters.

Page 11: Characters, Strings and the String Buffer Jim Burns.

Comparing String ValuesComparing String Values

The String class provides methods for The String class provides methods for comparing stringscomparing strings

In the example above the == sign is In the example above the == sign is comparing memory addresses, not the comparing memory addresses, not the actual strings.actual strings.

The String class The String class equals()equals() method method evaluates the contents of two String evaluates the contents of two String objects to determine if they are equivalent. objects to determine if they are equivalent.

Page 12: Characters, Strings and the String Buffer Jim Burns.

Import javax.swing.JOptionPane;Import javax.swing.JOptionPane;Public class CompareStringsPublic class CompareStrings{{

public static void main(String[] args)public static void main(String[] args){{

String aName = “Carmen”, anotherName;String aName = “Carmen”, anotherName;anotherName = JOptionPane. anotherName = JOptionPane.

showInputDialog(null, “Enter your name”);showInputDialog(null, “Enter your name”);if(aName.equals(anotherName))if(aName.equals(anotherName))JOptionPane.showMessageDialog(null, JOptionPane.showMessageDialog(null, aName aName

+ “ equals “ + anotherName);+ “ equals “ + anotherName);elseelseJOptionPane.showMessageDialog(null, aName JOptionPane.showMessageDialog(null, aName

+ “ does not equal “ + anotherName));+ “ does not equal “ + anotherName));System.exit(0);System.exit(0);

}}

Page 13: Characters, Strings and the String Buffer Jim Burns.

The The equals()equals() method method

From the code above, we can see that the From the code above, we can see that the equals()equals() method returns a Boolean value method returns a Boolean value of of truetrue or or falsefalse

Page 14: Characters, Strings and the String Buffer Jim Burns.

equalsIgnoreCase()equalsIgnoreCase() Method Method

Similar to the Similar to the equals()equals() method method Ignores caseIgnores case

String aName = “Roger”;String aName = “Roger”;

If(aName.equalsIgnoreCase(“roGER”))… If(aName.equalsIgnoreCase(“roGER”))…

evaluates to evaluates to truetrue

Page 15: Characters, Strings and the String Buffer Jim Burns.

compareTo() methodcompareTo() method

Returns an integer that is the numeric Returns an integer that is the numeric difference between the first two non-difference between the first two non-matching charactersmatching characters

Page 16: Characters, Strings and the String Buffer Jim Burns.
Page 17: Characters, Strings and the String Buffer Jim Burns.

Using other String MethodsUsing other String Methods

toUpperCase()toUpperCase() and and toLowerCase()toLowerCase() convert convert any String to its uppercase and lowercase any String to its uppercase and lowercase equivalentequivalent

Length()Length() returns the length of a String returns the length of a String

Page 18: Characters, Strings and the String Buffer Jim Burns.

import javax.swing.*;import javax.swing.*;public class BusinessLetterpublic class BusinessLetter{{ public static void main(String[] args)public static void main(String[] args) {{ String name;String name; String firstName = "";String firstName = ""; String familyName = "";String familyName = ""; int x;int x; char c;char c; name = JOptionPane.showInputDialog(null,name = JOptionPane.showInputDialog(null, "Please enter customer's first and last name"); "Please enter customer's first and last name"); x = 0;x = 0; while(x < name.length())while(x < name.length()) {{ if(name.charAt(x) == ' ')if(name.charAt(x) == ' ') {{ firstName = name.substring(0, x);firstName = name.substring(0, x); familyName = name.substring(x + 1, name.length());familyName = name.substring(x + 1, name.length()); x = name.length();x = name.length(); }} ++x;++x; }} JOptionPane.showMessageDialog(null,JOptionPane.showMessageDialog(null, "Dear " + firstName +"Dear " + firstName + ",\nI am so glad we are on a first name basis" +",\nI am so glad we are on a first name basis" + "\nbecause I would like the opportunity to" +"\nbecause I would like the opportunity to" + "\ntalk to you about an affordable insurance" +"\ntalk to you about an affordable insurance" + "\nprotection plan for the entire " + familyName + "\nprotection plan for the entire " + familyName + "\nfamily. Call A-One Family Insurance today" +"\nfamily. Call A-One Family Insurance today" + "\nat 1-800-555-9287.");"\nat 1-800-555-9287."); System.exit(0);System.exit(0); }} }}

Page 19: Characters, Strings and the String Buffer Jim Burns.

x = 0;x = 0; while(x < name.length())while(x < name.length()) {{ if(name.charAt(x) == ' ')if(name.charAt(x) == ' ') {{ firstName = name.substring(0, x);firstName = name.substring(0, x); familyName = name.substring(x + 1, familyName = name.substring(x + 1,

name.length());name.length()); x = name.length();x = name.length(); }} ++x;++x; }}

Page 20: Characters, Strings and the String Buffer Jim Burns.
Page 21: Characters, Strings and the String Buffer Jim Burns.

ConcatenationConcatenation

You know you can concatenate strings to You know you can concatenate strings to strings as in System.out.println(firstName strings as in System.out.println(firstName + “ “ + lastName);+ “ “ + lastName);

Page 22: Characters, Strings and the String Buffer Jim Burns.

Concatenation—numbers to strings Concatenation—numbers to strings by using +by using +

The following is permissible:The following is permissible:

Int myAge = 25;Int myAge = 25;

String aString = “My age is “ + myAge;String aString = “My age is “ + myAge;Another example would beAnother example would beString anotherString;String anotherString;

float someFloat = 12.34f;float someFloat = 12.34f;

anotherString = “” + someFloat;anotherString = “” + someFloat;

Page 23: Characters, Strings and the String Buffer Jim Burns.

Concatenation by using the Concatenation by using the toString()toString() method method

String theString;String theString;

Int someInt = 10;Int someInt = 10;

theString = Integer.toString(someInt);theString = Integer.toString(someInt);

String aString;String aString;

double someDouble = 8.25;double someDouble = 8.25;

aString = Double.toString(someDouble);aString = Double.toString(someDouble);

Page 24: Characters, Strings and the String Buffer Jim Burns.

Converting Strings to NumbersConverting Strings to Numbers

Use a wrapper like the Integer class which Use a wrapper like the Integer class which is a part of java.langis a part of java.lang

A wrapper is a class that is “wrapped A wrapper is a class that is “wrapped around” a simpler elementaround” a simpler element

Int anInt = Integer.parseInt(“649”) stores Int anInt = Integer.parseInt(“649”) stores the value 649 in the variable anIntthe value 649 in the variable anInt

Page 25: Characters, Strings and the String Buffer Jim Burns.

public class TestCharacterpublic class TestCharacter{{ public static void main(String[] args)public static void main(String[] args) {{ char aChar = 'C';char aChar = 'C'; System.out.println("The character is " + aChar);System.out.println("The character is " + aChar); if(Character.isUpperCase(aChar))if(Character.isUpperCase(aChar)) System.out.println(aChar + " is uppercase");System.out.println(aChar + " is uppercase"); elseelse System.out.println(aChar + " is not uppercase");System.out.println(aChar + " is not uppercase"); if(Character.isLowerCase(aChar))if(Character.isLowerCase(aChar)) System.out.println(aChar + " is lowercase");System.out.println(aChar + " is lowercase"); elseelse System.out.println(aChar + " is not lowercase");System.out.println(aChar + " is not lowercase"); aChar = Character.toLowerCase(aChar);aChar = Character.toLowerCase(aChar); System.out.println("After toLowerCase(), aChar is " + aChar);System.out.println("After toLowerCase(), aChar is " + aChar); aChar = Character.toUpperCase(aChar);aChar = Character.toUpperCase(aChar); System.out.println("After toUpperCase(), aChar is " + aChar);System.out.println("After toUpperCase(), aChar is " + aChar); if(Character.isLetterOrDigit(aChar))if(Character.isLetterOrDigit(aChar)) System.out.println(aChar + " is a letter or digit");System.out.println(aChar + " is a letter or digit"); elseelse System.out.println(aChar + " is neither a letter nor a digit");System.out.println(aChar + " is neither a letter nor a digit"); if(Character.isWhitespace(aChar))if(Character.isWhitespace(aChar)) System.out.println(aChar + " is whitespace");System.out.println(aChar + " is whitespace"); elseelse System.out.println(aChar + " is not whitespace");System.out.println(aChar + " is not whitespace"); }}}}

//see next slide//see next slide

Page 26: Characters, Strings and the String Buffer Jim Burns.

Test Character AppTest Character Apppublic class TestCharacterpublic class TestCharacter{{ public static void main(String[] args)public static void main(String[] args) {{ char aChar = 'C';char aChar = 'C'; System.out.println("The character is " + aChar);System.out.println("The character is " + aChar); if(Character.isUpperCase(aChar))if(Character.isUpperCase(aChar)) System.out.println(aChar + " is uppercase");System.out.println(aChar + " is uppercase"); elseelse System.out.println(aChar + " is not System.out.println(aChar + " is not

uppercase");uppercase"); if(Character.isLowerCase(aChar))if(Character.isLowerCase(aChar)) System.out.println(aChar + " is lowercase");System.out.println(aChar + " is lowercase"); elseelse

Page 27: Characters, Strings and the String Buffer Jim Burns.

System.out.println(aChar + " is not lowercase");System.out.println(aChar + " is not lowercase"); aChar = Character.toLowerCase(aChar);aChar = Character.toLowerCase(aChar); System.out.println("After toLowerCase(), aChar is " + System.out.println("After toLowerCase(), aChar is " +

aChar);aChar); aChar = Character.toUpperCase(aChar);aChar = Character.toUpperCase(aChar); System.out.println("After toUpperCase(), aChar is " + System.out.println("After toUpperCase(), aChar is " +

aChar);aChar); if(Character.isLetterOrDigit(aChar))if(Character.isLetterOrDigit(aChar)) System.out.println(aChar + " is a letter or digit");System.out.println(aChar + " is a letter or digit"); elseelse System.out.println(aChar + " is neither a letter nor a System.out.println(aChar + " is neither a letter nor a

digit");digit"); if(Character.isWhitespace(aChar))if(Character.isWhitespace(aChar)) System.out.println(aChar + " is whitespace");System.out.println(aChar + " is whitespace"); elseelse System.out.println(aChar + " is not whitespace");System.out.println(aChar + " is not whitespace"); }}}}

Page 28: Characters, Strings and the String Buffer Jim Burns.

Learning about the StringBuffer Learning about the StringBuffer ClassClass

Some strings are not constants, not immutableSome strings are not constants, not immutableString someChars = “Goodbye”;String someChars = “Goodbye”;someChars = “Goodbye Everybody”;someChars = “Goodbye Everybody”;someChars = “Goodbye” + “ Everybody”;someChars = “Goodbye” + “ Everybody”; You cannot change the string “Goodbye”You cannot change the string “Goodbye” To overcome these limitations, you can use the To overcome these limitations, you can use the

StringBuffer classStringBuffer class The StringBuffer class was invented to The StringBuffer class was invented to

accommodate strings that are not immutable accommodate strings that are not immutable (constants)(constants)

Page 29: Characters, Strings and the String Buffer Jim Burns.

The StringBuffer ClassThe StringBuffer ClassUses a buffer that is much larger than any Uses a buffer that is much larger than any

one string; actual size of the buffer is the one string; actual size of the buffer is the capacitycapacity

Provides methods that can change Provides methods that can change individual characters within a stringindividual characters within a string

Must initialize StringBuffer objects as Must initialize StringBuffer objects as follows:follows:StringBuffer eventString = new StringBuffer eventString = new

StringBuffer(“Hello there”);StringBuffer(“Hello there”);Cannot use Cannot use StringBuffer eventString = “Hello StringBuffer eventString = “Hello

there”;there”;

Page 30: Characters, Strings and the String Buffer Jim Burns.

Methods in the StringBuffer ClassMethods in the StringBuffer ClasssetLength()setLength() will change the length of a will change the length of a

String in a StringBuffer objectString in a StringBuffer objectcapacity()capacity() will find the capacity of an object will find the capacity of an objectHas four constructors:Has four constructors:

public StringBuffer()public StringBuffer() constructs a StringBuffer constructs a StringBuffer with no characters and a default size of 16 with no characters and a default size of 16 characterscharacters

public StringBuffer(int Capacity)public StringBuffer(int Capacity) creates a creates a StringBuffer with no characters and a capacity StringBuffer with no characters and a capacity defined by the parameterdefined by the parameter

public StringBuffer(String s)public StringBuffer(String s) contains the same contains the same characters as those stored in the String object scharacters as those stored in the String object s

Page 31: Characters, Strings and the String Buffer Jim Burns.

Still more methods in the Still more methods in the StringBuffer ClassStringBuffer Class

Append() lets you add characters to the Append() lets you add characters to the end of a StringBuffer objectend of a StringBuffer object

Insert() lets you add characters at a Insert() lets you add characters at a specific location within a StringBuffer specific location within a StringBuffer objectobjectStringBuffer someBuffer = new StringBuffer someBuffer = new

StringBuffer(“Happy Birthday);StringBuffer(“Happy Birthday);

someBuffer.insert(6,”30someBuffer.insert(6,”30thth “); “);

Produces “Happy 30Produces “Happy 30thth Birthday” Birthday”

Page 32: Characters, Strings and the String Buffer Jim Burns.

Still more methods in StringBufferStill more methods in StringBuffer

setCharAt() method allows you to change a setCharAt() method allows you to change a single character at a specified locationsingle character at a specified location someBuffer.setCharAt(6,’4’);someBuffer.setCharAt(6,’4’); Changes someBuffer to “Happy 40Changes someBuffer to “Happy 40thth Birthday” Birthday”

Can use charAt() method will return the Can use charAt() method will return the character at an offset number of positions from character at an offset number of positions from the first characterthe first character StringBuffer text = new StringBuffer(“Java StringBuffer text = new StringBuffer(“Java

Programming);Programming); Then text.charAt(5) returns the character ‘P’.Then text.charAt(5) returns the character ‘P’.

Page 33: Characters, Strings and the String Buffer Jim Burns.

packagepackage Strings; Strings;importimport javax.swing.*; javax.swing.*;publicpublic classclass RepairName { RepairName {

/**/** * * @param@param args args */*/publicpublic staticstatic voidvoid main(String[] args) main(String[] args) {{String name, saveOriginalName;String name, saveOriginalName;intint stringLength; stringLength;intint i; i;charchar c; c;name = JOptionPane.name = JOptionPane.showInputDialogshowInputDialog((nullnull, "Please enter your first and last name");, "Please enter your first and last name");saveOriginalName = name;saveOriginalName = name;stringLength = name.length();stringLength = name.length();forfor (i=0; i < stringLength; i++) (i=0; i < stringLength; i++){{c = name.charAt(i);c = name.charAt(i);ifif(i==0)(i==0){{c = Character.c = Character.toUpperCasetoUpperCase(c);(c);name = c + name.substring(1, stringLength);name = c + name.substring(1, stringLength);}}elseelseifif(name.charAt(i) == ' ')(name.charAt(i) == ' '){{++i;++i;c = name.charAt(i);c = name.charAt(i);c = Character.c = Character.toUpperCasetoUpperCase(c);(c);name = name.substring(0, i) + c + name.substring(i + 1, stringLength);name = name.substring(0, i) + c + name.substring(i + 1, stringLength);}}}}JOptionPane.JOptionPane.showMessageDialogshowMessageDialog((nullnull, "Original name was " + saveOriginalName + "\nRepaired name is " + name);, "Original name was " + saveOriginalName + "\nRepaired name is " + name);System.System.exitexit(0);(0);}}// // TODOTODO Auto-generated method stub Auto-generated method stub

}}


Recommended