Docsity

CS 106A Handout #24A: Solutions to Section #4 - String Manipulation Functions, Exercises of Programming Methodologies

Toggle sidebar
bg1
Mehran Sahami Handout #24A
CS 106A October 24, 2007
Solution to Section #4
Portions of this handout by Eric Roberts and Patrick Young
1. Adding commas to numeric strings
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?
pf2

Partial preview of the text

Download CS 106A Handout #24A: Solutions to Section #4 - String Manipulation Functions and more Exercises Programming Methodologies in PDF only on Docsity!

Mehran Sahami Handout #24A

CS 106A October 24, 2007

Solution to Section

Portions of this handout by Eric Roberts and Patrick Young

1. Adding commas to numeric strings

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?

  • 2 โ€“

3. Heap/Stack diagrams

1000 1 2

nu m den 1020 1 1

nu m den 1040 1 2

nu m den

r 1000^ FFC

heap

3^ FFB

1080^ FFB

n

1060 1 4

nu m den

stack i 3^ FFB result

1080 1 8

nu m den

x 1000^ FFB

garbage

4. Tracing method execution