CS 1302 – Chapter 4 (Review)
Mathematical Functions, Characters, & Strings
Reference Sections 4.3, 4.4, 4.6
Overview
- In this review material we consider how to use these methods from the Character and String classes:
4.3 – Character Data Type & Operations
- Character literals are specified with single quotes and string literals use double quotes:
charcode = 'B';
String name = "Leon";
- We use an escape sequence to represent special characters. In Java (and many languages) this is a backslash followed by a character (or digits). Several useful escape sequences are:
Escape Sequence / Name
\n / New line
\t / Tab
\\ / Backslash
\” / Double quote
For example:
String msg = "This is the \"first\" line\nThis is the second line";
System.out.println(msg);
Displays:
This is the "first" line
This is the second line
- Character Class – These are useful static methods: isDigit, isLetter, isLetterOrDigit, isLowerCase, isUpperCase, toLowerCase, toUpperCase. The first 5 return a Boolean and the last 2 return a character. For example:
charcode = 'a';
booleanisChar = Character.isLetter(code);
code = Character.toUpperCase(code);
- Comparing Characters – Since characters are represented internally as numbers, we can compare characters with: =, !=, <, <=, >, >=. For example:
charcode='Y';
if(code=='Y') {
...
}
4.4.1-4.4.4 – Strings 1
- String Class – Know these methods: length, charAt, concat, toUpperCase, toLowerCase, trim. For example:
Statement / Value
String msg = "If You "; / "If You "
intlen = msg.length(); / 7
charval = msg.charAt(3); / 'Y'
String msg2 = msg.trim(); / "If You"
intlen2 = msg2.length(); / 6
String msg3 = msg.toLowerCase(); / "if you "
String msg4 = msg2.concat(msg3); / "If Youif you "
String msg5 = msg2 + " " + msg3; / "If You if you "
- Example – Write a method, countUC that accepts a string and returns the number of upper case letters:
publicstaticint countUC(String str) {
intcount = 0;
for(inti=0; istr.length(); i++) {
if(Character.isUpperCase(str.charAt(i))) {
count++;
}
}
returncount;
}
- Example – Write a method, isLastCharSame that returns true if the last character in each of two input strings is the same.
publicstaticboolean isLastCharSame(String s1, String s2){
chare1 = s1.charAt(s1.length()-1);
chare2 = s2.charAt(s2.length()-1);
returne1==e2;
}
- Example – Write a method that returns whether a string is a palindrome.
publicstaticboolean isPalindrone( String s ){
intleft = 0;
intright = s.length()-1;
for(inti=0; is.length()/2; i++, left++, right--){
if( s.charAt(left)!=s.charAt(right))
returnfalse;
}
returntrue;
}
Homework:- Write a method, getUC that accepts a string and returns a string with just the upper case letters.
- Write a method, numsFirst that accepts a string and returns a string with all the digits in the input string first followed by all the letters. For example: “1a2b3c” returns “123abc”, and “xyz 456” returns “456xyz”.
- Write a method, isNumber that accepts a string and returns true if the string is an integer and false otherwise.
- Write a method, isPalindrone2 that accepts a string and returns whether the string is a palindrome ignoring spaces. For example: “a bc cba” returns true. Note that this example has 1 space between and the “a” and “b” and 2 spaces between the two “c”s. Hint: write a helper method to remove the spaces from a string and then call isPalindrone.
4.4.7 – Strings 2
- String Class – Know these comparison methods: equals, compareTo, contains. For example:
Statement / Description
s1.equals(s2); / Returns true if s1 has the same contents as s2 and false otherwise.
s1.compareTo(s2); / Returns a negative integer if s1<s2, 0 if they are the same, and a positive number if s1>s2.
s1.contains(s3); / Returns true if the substring s3 is contained in s1 and false otherwise.
For example:
String s1 = "anteater";
String s2 = "buffalo";
String s3 = "eat";
System.out.println(s1.equals(s2));// false
System.out.println(s1.compareTo(s2));// -1
System.out.println("a".compareTo("A"));// 32, upper case occurs before lower case
System.out.println(s1.contains(s3));// true
- Do not use: if(s1==s2)to check if two strings have the same contents. When you use “==”, the JVM checks to see if the two objects occupy the same location in memory, not to see if the contents of the strings are the same.
Homework:
- Write a method, countStrings, that accepts an array of strings and and another string, key. The method should return the number of strings in the array that have the same contents as key.
4.4.8 – Strings 3
- String Class – Know thesubstring method:
Statement / Description
s1.substring(beg); / Returns the substring in s1 that beings at index beg and extends to the end of the string.
s1.substring(beg,end); / Returns the substring in s1 that begins at index beg and extends to the character at index end-1.
For example:
String s1 = "anteater";
String s2 = s1.substring(3);// "eater"
String s3 = s1.substring(3,6);// "eat"
Homework:- Write a method, getOutside that accepts a string and two integers, loc1 and loc2. The method should return a string composed of the characters that are not between (inclusive) loc1 and loc2. For example:
If loc1>loc2 or loc1 or loc2 is not a valid position in the string, then return an empty string.
- Write a method, reverseHalf that accepts a string and returns a string with the right half of the input string first, followed be the left half of the input string.
reverseHalf(“abcde”) returns: “deabc”
As the later example shows, if the string has odd length then the middle character belongs in the left portion.
- Assume you have a string, s1 that is at least 2 characters long. Write a snippet of code that uses the substring method to return the substring that excludes the first and last characters. For example: if s1=”abcdef” then the answer would be s2=”bcde”.
- A string, s1 begins with an integer product code followed by a description. Write a snippet of code that uses the substring method to create a new string containing just the description. Example: s1=”4432Night Vision Googles” would return s2=”Night Vision Googles”
- A string, valcontains any number of characters. Write a snippet of code that uses the substring method that defines a new string, result that contains every other set of 3 characters in val. If there is not an ending 3-tuple, then extract whatever is there (either 1 or 2 characters). Examples:
abc123def / abcdef
123abcde / 123de
a / a
4.4.9– Strings 4
- String Class – Know these methods: indexOf, and lastIndexOf and their overloaded versions:
Statement / Description
s1.indexOf(s2); / Returns the index of the first occurrence of s2 in s1 or -1 if not found. Overloaded version accepts a character.
s1.indexOf(s2,from); / Returns the index of the first occurrence of s2 in s1 which occurs at or after the index from, or -1 if not found. Overloaded version accepts a character.
s1.lastIndexOf(s2); / Returns the index of the last occurrence of s2 in s1 or -1 if not found. Overloaded version accepts a character.
s1.lastIndexOf(s2,from); / Returns the index of the last occurrence of s2 in s1 which occurs at or before the index from, or -1 if not found. Overloaded version accepts a character.
For example:
String s1 = "anteater";
a / n / t / e / a / t / e / r0 / 1 / 2 / 3 / 4 / 5 / 6 / 7
String s1 = "anteater";
inta = s1.indexOf('e');// 3
intb = s1.indexOf('e',a+1);// 6
intc = s1.indexOf("ate");// 4
intd = s1.indexOf('z');// -1
inte = s1.lastIndexOf('a');// 4
intf = s1.lastIndexOf('a',3);// 0
- Example – A string contains two substrings separated by a comma. Write a method, combine that accepts such a string and returns the two substrings concatenated. Example: “abc,def” returns “abcdef”.
publicstatic String combine(String s1){
intpos = s1.indexOf(',');
String substr1 = s1.substring(0, pos);
String substr2 = s1.substring(pos+1);
returnsubstr1 + substr2;
}
- Example – Write a method, countDotCom that counts how many times the sequence “.com” appears in an input string. For example: “abc.co ddd.com .com pp.ceg.com f” returns the value: 3.
publicstaticint countDotCom(String s1){
intcount = 0;
intpos = s1.indexOf(".com");
while( pos != -1) {
count++;
pos = s1.indexOf(".com", pos+4);
}
returncount;
}
or
publicstaticint countDotCom2( String s1 ){
intcount = 0;
intpos = s1.indexOf(".com");
while( pos != -1) {
count++;
s1 = s1.substring(pos+4);
pos = s1.indexOf(".com");
}
returncount;
}
- Example – Write a method, uniqueChars that accepts a string and returns a string with exactly one instance of each character from the input string, in the order they occur. For example: “abbcKczza” returns “abcKz”.
publicstatic String uniqueChars( String s ){
String result = "";
for( inti=0; is.length(); i++ ) {
charc = s.charAt(i);
if( result.indexOf(c)==-1)
result += c;
}
returnresult;
}
Homework:- A string contains three substrings separated by a comma. Write a method, combine3 that accepts such a string and returns the three substrings concatenated. Example: “ab,cdefg,hi” returns “abcdefghi”.
- Write a method, countOccurrences that accepts a two strings and returns the number of times the second string is found in the first string. For example, if the input is: “The car is a car but not a car, but sometimes a car or balloon” and “car”, then the method will return 4.
- Consider a short version of a URL. For example the URL: “google.com” is composed of “google” which is the domain name and “com” which is the top-level domain. A string contains a number of URLs each with the top-level domain, “com”. Write a method, domainNames that accepts such a string and returns a string of domain names separated by commas. Example: “google.comnytimes.comoracle.com” returns “google,nytimes,oracle”.
- Write a method, vowels that accepts a string and returns a string that contains the vowels (a,e,i,o,u) in the input string. For example: “The dog ate cereal” would return: “eoa”.
4.4.10– Conversion between Strings & Numbers
- To convert a string which is a number, use one of these below. If the string is not a number (or the wrong type) a run-time error will result.
String s1 = "48";
intx = Integer.parseInt(s1);
String s2 = "933.92";
doubley = Double.parseDouble(s2);
- To convert a number to a string, concatenate an empty string to the number:
String s3 = y + "";
Or, use:
String s4 = String.valueOf(y);
- Example – A string contains two integers separated by a comma. Write a method, sum that accepts such a string and returns the sum of the two integers.
publicstaticint sum(String s1){
intpos = s1.indexOf(',');
String strNum1 = s1.substring(0, pos);
String strNum2 = s1.substring(pos+1);
intnum1 = Integer.parseInt(strNum1);
intnum2 = Integer.parseInt(strNum2);
intsum = num1 + num2;
returnsum;
}
- Example – A string contains two integers separated by a comma. Suppose the first integer is 3, you will write a method, subInteger that returns the integer composed of the first 3 digits in the second integer. Example: “3,12345” returns 123; “10,123456789012345” returns 1234567890.
publicstaticint subInteger( String s1 ){
intpos = s1.indexOf(',');
intlen = Integer.parseInt(s1.substring(0, pos));
intnum = Integer.parseInt(s1.substring(pos+1, pos+len+1));
returnnum;
}
Homework:- A string contains three integers separated by a comma. Write a method, sum that accepts such a string and returns the sum of the three integers.
- A string contains two integers separated by a comma. Write a method, newNum that accepts such a string and returns the integer composed of the last digit of the first number and the first digit of the second number. Example: “123,456” returns 34.
4.6 – Formatting Output – String.format method
- The String class defines the static method, format which returns a formatted string. The syntax is:
String result = String.format( “format string” [, arg1, arg2, … ] );
The format string is composed of string literals and format specifiers. Format specifiers define how to format the arguments. Example:
Notice that there is one format specifier for each argument.
- In the example above, “%.2f” is a format specifier which has this meaning
Symbol / Meaning
% / Signifies the beginning of a format specifier. The value of a variable will be placed here
.2 / Provide two decimal places
f / The value is a floating (double) point number
The common format specifiers are:
Symbol / Meaningf / Floating point number
d / Integer number
s / String
A quick reference can be found here:
- Example – Write a method, twoPerLine that accepts an array of doubles and returns a string with the numbers two-per line, separated by a comma, and two decimal places. Assume the array has an even number of values.
publicstatic String twoPerLine( double[] vals ){
String s = "";
for( inti=0; ivals.length; i+=2) {
String newLine = String.format("%.2f, %.2f \n", vals[i], vals[i+1]);
s += newLine;
}
returns;
}
- Example – Write a method, printArray that accepts an array of doubles and an integer, numDec. The method should return a string with each value on a separate line and containing numDec decimals. Hint: the format specifier is a string, so build it programmatically:
String fmt = “%.” + numDec + “f\n”;
String newline = String.format( fmt, vals[i] );
Solution:
publicstatic String printArray(double[] vals, intnumDecimals){
String format = "%." + numDecimals + "f\n";
String result = "";
for(doubled : vals){
result += String.format(format, d);
}
returnresult;
}
- The format specifier for a floating point number can also take the width of the space to print the number:
% width . decimals f
For example, with a field width of 8:
doublex = 498.57334;
result = String.format("x=%8.2f", x);
System.out.println(result);
The result will be right-justified in 8 columns as shown below:
You can also use a flag to left-justify and if the field is not wide enough, java just expands it so that the whole number is displayed.
Another example: suppose you have an array of doubles and all numbers are are less than 1000, you could print them with two decimals so that the decimals lined up using a width=6. For example:
Code / Outputdouble[] vals = {498.56721, 4.3318, 27.921362};
for(inti=0; ivals.length; i++) {
System.out.printf("%6.2f\n", vals[i]);
} / 498.57
4.33
27.92
- The format specifier for a floating point number can also take a comma to indicate to use a comma as the thousand’s separator:
% , . decimals f
For example,
doublesalary = 78224.8230842;
result = String.format("Salary=$%,.2f", salary);
Which produces: Salary=$78,224.82
Note that the “$” is not a part of the format specifier, it is a string literal.
Homework:- Write a method, buildReport that accepts: an array of strings, names; an array of ints, ages; and an array of doubles, salaries. The size of each array is the same. The method should use String.format to build and return a string that shows each name, age, and salary on a single line in a format like this:
Name: Keisha, age:33, salary: $68,992.92
Name: Jaylen, age:44, salary: $121,042.04
- Write a method, formatWeightsthat accepts a double array of weights and an integer, n. The method will return a string with the weights all on a single line, separated by a single space, and having n decimals. Hint: a format string is a string, so you should build it programmatically. If n=3, then the result will look like this, for example:
- Java defines a printf method which is used to achieve a formatted print. The syntax is:
System.out.printf( “format string” [, arg1, arg2, … ] );
The arguments to the method are identical to the arguments for String.format.
Example:
Code / Outputx=49.56721;
System.out.printf("x=%.2f\n", x); / x=49.57
Homework:
- Write a method, print2Decimals that accepts an array of doubles and prints the numbers with exactly two decimal places.
- Write a method, print2Decimals2 that accepts an array of doubles and prints the numbers in standard currency format, one per line, such that the decimals all line up. Assume all numbers have 3 or fewer digits before the decimal. For example, [334.4322334, 5.89232, 74.735194] prints like this:
$ 5.89
$ 74.73
1