You are on page 1of 13

http://technicalsupportindia.blogspot.

com/

Mehran Sahami CS 106A

Strings Examples

Handout #25 October 22, 2007

Based on examples by Eric Roberts and Patrick Young.

Checking for palindromes


public boolean isPalindrome(String str) { for(int i = 0; i < str.length() / 2; i++) { if (str.charAt(i) != str.charAt(str.length() - (i + 1))) { return false; } } return true; }

Reversing strings and a simpler version of checking for palindromes


public String reverseString(String str) { String result = ""; for(int i = 0 ; i < str.length(); i++) { result = str.charAt(i) + result; } return result; } public boolean simpleIsPalindrome(String str) { return (str.equals(reverseString(str))); }

Counting uppercase characters


import acm.program.*; public class CountUppercase extends ConsoleProgram { private int countUppercase(String str) { int upperCount = 0; for(int i=0; i<str.length(); i++) { char ch = str.charAt(i); if (Character.isUpperCase(ch)) { upperCount++; } } return upperCount; } public void run() { String str = readLine("Enter String: "); println(countUppercase(str) + " upper case letters"); }

http://technicalsupportindia.blogspot.com/
2 Replace first occurrence
public String replaceFirstOccurrence(String str, String orig, String repl) { int index = str.indexOf(orig); if (index != -1) { str = str.substring(0, index) + repl + str.substring(index + orig.length()); } return str; }

http://technicalsupportindia.blogspot.com/

Mehran Sahami CS 106A

Section Handout #4: String Processing

Handout #24 October 22, 2007

Portions of this handout by Eric Roberts and Patrick Young

1. Adding commas to numeric strings (Chapter 8, Exercise 13, page 290) When large numbers are written out on paper, it is traditional at least in the United States to use commas to separate the digits into groups of three. For example, the number one million is usually written in the following form:
1,000,000

To make it easier for programmers to display numbers in this fashion, implement a method
private String addCommasToNumericString(String digits)

that takes a string of decimal digits representing a number and returns the string formed by inserting commas at every third position, starting on the right. For example, if you were to execute the main program
public void run() { while (true) { String digits = readLine("Enter a numeric string: "); if (digits.length() == 0) break; println(addCommasToNumericString(digits)); } }

your implementation of the addCommasToNumericString method should be able to produce the following sample run:

http://technicalsupportindia.blogspot.com/
2 2. Deleting characters from a string Write a method
public String removeAllOccurrences(String str, char ch)

that removes all occurrences of the character ch from the string str. For example, your method should return the values shown:
removeAllOccurrences("This is a test", 't') UHWXUQV removeAllOccurrences("Summer is here!", 'e') UHWXUQV removeAllOccurrences("---0---", '-') UHWXUQV "This is a es" "Summr is hr" "0"

3. Heap/stack diagrams Using the style of heap/stack diagram introduced in Chapter 7, show the state of both the heap and the stack at the point in the computation indicated by the arrow in the following code, where the Rationale class is the one defined in Chapter 6.
public void run() { Rational r = new Rational(1, 2); r = raiseToPower(r, 3); println("r ^ 3 = " + r); } private Rational raiseToPower(Rational x, int n) Rational result = new Rational(1); for (int i = 0; i < n; i++) { result = result.multiply(x); } 'LDJUDPDWWKLVSRLQW return result; }

Indicate which values in the heap are garbage at this point in the calculation.

http://technicalsupportindia.blogspot.com/
3 4. Tracing method execution For the program below, show what output is produced by the program when it runs.
/* * File: Mystery.java * -----------------* This program doesn't do anything useful and exists only to test * your understanding of method calls and parameter passing. */ import acm.program.*; public class Mystery extends ConsoleProgram { public void run() { ghost(13); } private void ghost(int x) { int y = 0; for (int i = 1; i < x; i *= 2) { y = witch(y, skeleton(x, i)); } } println("ghost: x = " + x + ", y = " + y);

private int witch(int x, int y) { x = 10 * x + y; println("witch: x = " + x + ", y = " + y); return x; } private int skeleton(int x, int y) { return x / y % 2; }

http://technicalsupportindia.blogspot.com/

Mehran Sahami CS 106A

Solution to Section #4

Handout #24A October 24, 2007

1. Adding commas to numeric strings

Portions of this handout by Eric Roberts and Patrick Young

private String addCommasToNumericString(String digits) { String result = ""; int len = digits.length(); int nDigits = 0; for (int i = len - 1; i >= 0; i--) { result = digits.charAt(i) + result; nDigits++; if (((nDigits % 3) == 0) && (i > 0)) { result = "," + result; } } return result; }

2. Deleting characters from a string


private String removeAllOccurrences(String str, char ch) { String result = ""; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != ch) { result += str.charAt(i); } } return result; }

A slightly different approach that involves a while loop instead of a for loop:
private String removeAllOccurrences(String str, char ch) { while (true) { int pos = str.indexOf(ch); if (pos >= 0) { str = str.substring(0, pos) + str.substring(pos + 1); } else break; } return str; }

Could you generalize these functions to remove substrings? For instance, removeAllSubstrings("Mississippi", 'si') returns "Missppi". Would these two functions ever return different values for the same input?

http://technicalsupportindia.blogspot.com/
2 3. Heap/Stack diagrams
1000

1020

1040

FFB0 1060 FFB4 FFB8 FFB8 1080 FFC0

4. Tracing method execution

http://technicalsupportindia.blogspot.com/

http://technicalsupportindia.blogspot.com/

http://technicalsupportindia.blogspot.com/

http://technicalsupportindia.blogspot.com/

http://technicalsupportindia.blogspot.com/

http://technicalsupportindia.blogspot.com/