valdosta state university · web viewthat accepts an array of strings and returns the smallest,...

22
CS 1302 – Chapter 4 (Review) Mathematical Functions, Characters, & Strings Reference Sections 4.3, 4.4, 4.6 Overview 1. In this review material we consider how to use some methods from the Character and String classes: 4.3 – Character Data Type & Operations 2. char is a primitive data type. A character literal is specified with single quotes. For example: char code = 'B'; char[] codes = {'C','a','G','T','f'}; 3. The Character class defines a number of useful static methods as shown in the class diagram on the right. It should be obvious what they do. A note on the syntax of the class diagram: char code = 'a'; boolean isChar = Character.isLetter(code); code = Character.toUpperCase(code); 4. Comparing Characters – Since characters are represented internally as numbers, we can compare characters with: =, !=, <, <=, >, >=. 5. Example – Write a method, makeUpperCase that accepts a character array and makes all the elements upper case. public static void makeUpperCase(char[] codes) { for(int i=0; i<codes.length; i++) { if(Character.isLowerCase(codes[i])) { 1

Upload: others

Post on 08-Sep-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

CS 1302 – Chapter 4 (Review)Mathematical Functions, Characters, & Strings

Reference Sections 4.3, 4.4, 4.6

Overview

1. In this review material we consider how to use some methods from the Character and String classes:

4.3 – Character Data Type & Operations

2. char is a primitive data type. A character literal is specified with single quotes. For example:

char code = 'B';char[] codes = {'C','a','G','T','f'};

3. The Character class defines a number of useful static methods as shown in the class diagram on the right. It should be obvious what they do. A note on the syntax of the class diagram:

char code = 'a';boolean isChar = Character.isLetter(code);code = Character.toUpperCase(code);

4. Comparing Characters – Since characters are represented internally as numbers, we can compare characters with: =, !=, <, <=, >, >=.

5. Example – Write a method, makeUpperCase that accepts a character array and makes all the elements upper case.

public static void makeUpperCase(char[] codes) {for(int i=0; i<codes.length; i++) {

if(Character.isLowerCase(codes[i])) {char c = Character.toUpperCase(codes[i]);codes[i] = c;

}}

}

Best Practices:a. The name of an array should always be pluralb. Method and variable names use camel case

1

Page 2: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

c. A method that returns a boolean should begin with a “is”, as in isLowerCase. Sometimes these prefixes are more suitable: “has”, “can”, “should”. This is also true for boolean variables.

d. A boolean method (or expression) returns true or false. Thus, in an if statement you should not check to see if it is true (or false). For example:

Preferred Not Preferredif(Character.isLowerCase(codes[i

if(Character.isLowerCase(codes[i])==tr

if(!Character.isLetterOrDigit(c))

if(Character.isLetterOrDigit(c)==false

6. Write a method, countAAndZ that accepts a character array and returns the number of characters in the array that are either ‘A’ or ‘Z’.

public static int countAAndZ(char[] codes) {int count = 0;for(int i=0; i<codes.length; i++) {

char c = codes[i];if( c=='A' || c=='Z' ) {

count++;}

}return count;

}

4.4.1-4.4.4 – Strings 1

7. String is a class in Java. In this chapter, we study the methods shown in the class diagram on the right. We usually create a String by assigning it to a string literal:

String s = "buffalo";

However, we can use the constructor:

String s = new String("buffalo");

8. 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:

Code OutputString msg = "The \"first\"\nThe second ";

The "first"The second

2

Page 3: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

System.out.println(msg);9. String Class – Know these methods: length, charAt, concat, toUpperCase, toLowerCase, trim. For example:

Method Descriptionlength():int Returns the length of the string, the number of characters.charAt(i:int):char Returns the character at index i in the string.trim():String Returns a string whose value is this string with any leading or trailing whitespace

removed.toUpperCase():String Returns a string whose value is this string and with all the characters being

converted to upper case.toLowerCase():String Returns a string whose value is this string and with all the characters being

converted to lower case.concat(s:String):String

Returns a string whose value is this string with s concatenated to the end. Usually we just use the “+” operator to concatenate strings. Both of these are equivalent:

String s1 = "anteater";String s2 = "buffalo";

String s3 = s1 + s2;String s4 = s1.concat(s2);

10. Example – Write a method, countUC that accepts a string and returns the number of upper case letters in the string.

public static int countUC(String str) {int count = 0;for(int i=0; i<str.length(); i++) {

if(Character.isUpperCase(str.charAt(i))) {count++;

}}return count;

}

11. Example – Write a method, isLastCharSame that returns true if the last character in each of two input strings is the same.

public static boolean isLastCharSame(String s1, String s2){char e1 = s1.charAt(s1.length()-1);char e2 = s2.charAt(s2.length()-1);return e1==e2;

}

12. Example – Write a method that returns whether a string is a palindrome.

public static boolean isPalindrone( String s ){int left = 0;int right = s.length()-1;

for(int i=0; i<s.length()/2; i++, left++, right--){if( s.charAt(left)!=s.charAt(right))

return false;}return true;

3

Page 4: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

}Homework:

1. Write a method, getUC that accepts a string and returns a string with just the upper case letters. For example: getUC(“aBcDe”) would return “BD”

2. 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”.

3. Write a method, isNumber that accepts a string and returns true if the string is an integer and false otherwise. Hint: all the characters need to be digits.

4. Write a method, countVowels that accepts a string and returns the total number of vowels (a,e,i,o,u) in the string. Hint: (a) define a char array in method that defines the five vowels, (b) loop over each character in string, and for each character, loop over vowels array to see if one of them matches the character. For example:

countVowels("Thgvlm")=0countVowels("Thez")=1countVowels("eaterallyou")=6

5. 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 written in the notes above.

4.4.7 – Strings 2 – Comparison Methods

13. These are several comparison methods in the String class

Method Descriptionequals(s:String):boolean

Returns true if s has exactly the same contents as this string.

contains(s:String):boolean

Returns true if s is in this string. Note: there is not an overload that accepts a character.

compareTo(s:String):int Returns a negative integer if this string is lexicographically less than s, a positive integer if this string is greater than s, and 0 if they are the same.

14. Characters are represented by Unicode values (integers). The lexicographic order of these are: 0, 1, 2, …, A, B, C, …, a, b, c. Note that the upper case characters are before the lower case characters.

a. The compareTo(s:String) method starts at the beginning of this string and s and finds the first character that is different between the two. It uses this character to see which string is smaller. It is easier to see with the examples below. Finally, it returns 0 if the two strings are equal.

String s1 = "ant";String s2 = "fox";String s3 = "alpaca";String s4 = "ant";

System.out.println(s1.compareTo(s2)); // -5System.out.println(s2.compareTo(s1)); // 5System.out.println(s1.compareTo(s3)); // 2System.out.println(s1.compareTo(s4)); // 0

4

Page 5: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

5

Page 6: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

b. As noted above, the upper case characters occur before the lower case letters. For example:

String s1 = "fox";String s2 = "Fox";

System.out.println(s1.compareTo(s2)); // 26

c. The compareToIgnoreCase(s:String) method is the same as compareTo except that it ignores case differences. For example:

String s1 = "fox";String s2 = "Fox";String s3 = "FOx";String s4 = "falcon";

System.out.println(s1.compareToIgnoreCase(s2)); // 0System.out.println(s3.compareToIgnoreCase(s4)); // 14

15. Do NOT use “==” to compare the contents of two strings. 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. In other words, do this:

Do This: Not This:if(s1.equals(s2)) if(s1==s2)

Homework:

6. 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.

7. Write a method, findSmallestString, that accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case.

4.4.8 – Strings 3 – Substring Methods

16. The String class has methods for returning a substring:

Method Descriptionsubstring(beg:int):String Returns the substring in this string that beings at index beg and

extends to the end of the string.substring(beg:int,end:int):String

Returns the substring in this string that begins at index beg and extends to the character at index end-1. Thus, the length of the returned string will be end-beg.

For example:

String s1 = "anteater";String s2 = s1.substring(3); // "eater"String s3 = s1.substring(3,6); // "eat"

6

Page 7: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

Homework:

8. Write a method, trimFirstAndLast that accepts a string and returns a string with the same contents as the input string except that the first and last characters are removed. Must use substring, can’t use charAt. You can assume the input string has at least 2 characters. Hint: the method body is one line of code. For example:

trimFirstAndLast (“uengines”) returns: “engine”

9. 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. Must use substring, can’t use charAt.

reverseHalf(“abcdef”) returns: “defabc”reverseHalf(“abcde”) returns: “cdeab”

As the later example shows, if the string has odd length then the middle character is considered the first character in the right half.

10. 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. Must use substring, can’t use charAt. For example:

getOutside(“DogzqfgZebra”,3,6) returns: “DogZebra”

If loc1>loc2 or loc1 or loc2 is not a valid position in the string, then return an empty string.

11. 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 produce s2=”Night Vision Googles”. You will need charAt, but you must also use substring.

12. Write a method, everyOther3Tuple that accepts a string. You can assume this string has a length that is a multiple of 3. The method should return a string that contains every other 3-tuple. For example:

everyOther3Tuple("abc")="abc"everyOther3Tuple("abcVVVdef")="abcdef"everyOther3Tuple("abcVVVdefTTT")="abcdef"everyOther3Tuple("abcVVVdefTTTghi")="abcdefghi"

4.4.9– Strings 4, Substring Location Methods

17. These methods in the String class return the location of an input string inside this string

Method DescriptionindexOf(c:char):intindexOf(s:String):int

Returns the index of the first occurrence of c (s) in this string or -1 if not found.

indexOf(c:char,from:int):intindexOf(s:String,from:int):int

Returns the index of the first occurrence of c (s) in this string which occurs at or after the index from, or -1 if not found.

lastIndexOf(c:char):intlastIndexOf(s:String):int

Returns the index of the last occurrence of c (s) in this string or -1 if not found.

lastIndexOf(c:char,from:int):intlastIndexOf(s:String,from:int):int

Returns the index of the last occurrence of c (s) in this string searching backwards starting at from.

7

Page 8: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

For example:

String s1 = "anteater";

a n t e a t e r0 1 2 3 4 5 6 7

int a = s1.indexOf('e'); // 3int b = s1.indexOf("ate"); // 4int c = s1.indexOf("bill"); // -1int d = s1.indexOf("te", 3); // 5int e = s1.lastIndexOf("te"); // 5int f = s1.lastIndexOf('a',3); // 0

18. Example – Write a method, combine that accepts a string. This string contains two substrings separated by a comma. The method should return the two substrings concatenated. Example: “abc,def” returns “abcdef”.

public static String combine(String s1){int pos = s1.indexOf(',');String substr1 = s1.substring(0, pos);String substr2 = s1.substring(pos+1);return substr1 + substr2;

}

19. 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.

public static int countDotCom(String val){int count=0;int beg=0;

while(beg<=val.length()-4) {int pos = val.indexOf(".com", beg);if(pos==-1) return count;count++;beg=pos+4;

}return count;

}

20. 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”.

public static String uniqueChars(String s) {String result = "";for(int i=0; i<s.length(); i++) {

char c = s.charAt(i);if(result.indexOf(c)==-1)

result += c;}return result;

}

Homework:

13. A string contains three substrings separated by a comma. Write a method, combine3 that accepts such a

8

Page 9: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

string and returns the three substrings concatenated. Example: “ab,cdefg,hi” returns “abcdefghi”.

combine3("abc,def,ghi")="abcdefghi"combine3("1,2,3")="123"combine3("Coding ,is , cool")="Coding is cool"combine3(",ab,de")="abde"combine3(",,aab")="aab"combine3("abc,,4")="abc4"

14. Write a method, findFurthestLocation that accepts a string and an array of characters. The method should return the furthest location in the string where one of the characters in the array occurs. For example:

findFurthestLocation(abcdeaeafdah,[e, a, d])=10 // ‘a’ was the furthestfindFurthestLocation(abcdeaeafdah,[q, e, z])=6 // ‘e’ was the furthestfindFurthestLocation(abcdeaeafdah,[1, 2, 3])=-1 // none were found

15. Write a method, findLocations that accepts a string and a character. The method should return the an array with the locations of the first 5 occurrences of the character in the string. If there are less than 5 occurrences, then -1 should be used to fill the return array. For example:

findLocations(ab,a)=[0, -1, -1, -1, -1]findLocations(aab,a)=[0, 1, -1, -1, -1]findLocations(aba,a)=[0, 2, -1, -1, -1]findLocations(babbaabacde,a)=[1, 4, 5, 7, -1]findLocations(babbaabacdaffaage,a)=[1, 4, 5, 7, 10]

16. Write a method, getVowels that accepts a string and returns a string that contains the vowels (a,e,i,o,u) in the input string. Only one occurrence of each vowel found should be returned. Hint: (a) define a string that contains all the vowels, “aeiou”, (b) loop over characters in string, (c) use indexOf to see if character is in vowels, (d) use indexOf to see if character is already in result, (e) can’t use contains as it only accepts a string. (f) there are other approaches. For example:

getVowels("The dog ate cereal")="eoa"getVowels("aeiou")="aeiou"getVowels("a a a a e")="ae"getVowels("Zxylpls")=""

17. 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:

countOccurrences("circus time",'clown')=0countOccurrences("car is a car is a car but not a cat",'car')=3countOccurrences("atatat3",'at')=3

18. 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. For example:

getDomainName("abcdefg")="")getDomainName("abc.com")="abc")getDomainName("a.comb.com")="a,b")getDomainName("a.comb.comc.com")="a,b,c")

9

Page 10: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

getDomainName("google.comnytimes.comoracle.com")="google,nytimes,oracle")4.4.10– Conversion between Strings & Numbers

21. 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";int x = Integer.parseInt(s1);

String s2 = "933.92";double y = Double.parseDouble(s2);

22. To convert a number to a string, concatenate an empty string to the number:

Number to String Character to String Boolean to Stringdouble x = 43.42;String s1 = String.valueOf(x);// OrString s2 = "" + x;

char c = 'B';String s3 = String.valueOf(c);// OrString s4 = "" + c;

boolean isValid = true;String s5 = String.valueOf(isValid);// OrString s6 = "" + isValid;

23. 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.

public static int sum(String s1){int pos = s1.indexOf(',');

String strNum1 = s1.substring(0, pos);String strNum2 = s1.substring(pos+1);

int num1 = Integer.parseInt(strNum1);int num2 = Integer.parseInt(strNum2);int sum = num1 + num2;return sum;

}

24. 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.

public static int subInteger( String s1 ){int pos = s1.indexOf(',');int len = Integer.parseInt(s1.substring(0, pos));int num = Integer.parseInt(s1.substring(pos+1, pos+len+1));return num;

}

10

Page 11: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

Homework:

19. A string contains a decimal number represented in European format (using a comma for the decimal separator. Write a method, convertToDecimal which accepts such a string and returns the United States representation of the number as a double. For example:

convertToDecimal("3,333")=3.333convertToDecimal("0,123")=0.123convertToDecimal("222,0")=222.000

20. 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. For example:

newNum("123,456")=34newNum("1,9")=19newNum("3,745")=37newNum("59,2")=92,

21. A string contains a binary number. Write a method, binaryToDecimal that accepts such a string. The method should convert this number to its decimal representation and return it as a double. For example:

binaryToDecimal("0000")=0binaryToDecimal("0001")=1binaryToDecimal("0011")=3binaryToDecimal("0111")=7binaryToDecimal("1101")=13binaryToDecimal("101010")=42

22. A string contains two decimal numbers separated by an arithmetic operator (+,-,*,/). Write a method, artihmeticOperation that accepts such a string and returns the result of applying the operator to the two decimal numbers. For example:

artihmeticOperation("3.333+6.667")=10.000artihmeticOperation("1-1")=0.000artihmeticOperation("3.333*6")=19.998artihmeticOperation("12.5/6.25")=2.000

11

Page 12: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

4.6 – Formatting Output – String.format method

25. 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 and that String.format returns the format string with the arguments substituted for the format specifiers.

26. In the example above, there are 3 format specifiers

a. “%s”

Symbol Meaning% Signifies the beginning of a format specifier. s The argument is a string or character

b. “%d”

Symbol Meaningd The argument is an integer

c. “%.2f”

Symbol Meaning.2 Round argument to two decimal placesf The value is a floating (double) point number

A quick reference can be found here:

https://www.cs.colostate.edu/~cs160/.Summer16/resources/Java_printf_method_quick_reference.pdf

12

Page 13: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

27. Example – Write a method, formatArray that accepts an array of doubles and returns a string with the (a) numbers all in a single line each separated by a comma, (b) each number prefaced with, “ht=”, (c) two decimal places, and (d) no trailing comma. For example, the string that is returned will look like this:

"ht=334.43, ht=5.89, ht=74.74, ht=8.50"

public static String formatArray(double[] vals){String result = "";for(int i=0; i<vals.length; i++) {

String num = String.format("ht=%.2f, ", vals[i]);result += num;

}return result.substring(0,result.length()-2);

}

28. 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

29. Example

Code Output

double salary = 78224.8230842;result = String.format("Salary=$%,.2f", salary);

Salary=$78,224.82

Note that the “$” is not a part of the format specifier, it is a string literal.

30. Note that the format string is a String. This means that we can build it programmatically. For example:

double num = 34.29368745;int numDec=3;String formatString = "ht=%." + numDec + "f, ";String formattedNum = String.format(formatString, num);

31. Example – Write an overloaded method, formatArray from above that accepts an array of doubles and an integer. The integer represents the desired number of decimals in the output.

public static String formatArray( double[] vals, int numDec ){String result = "";String formatString = "ht=%." + numDec + "f, ";

for(int i=0; i<vals.length; i++) {String num = String.format(formatString, vals[i]);result += num;

}return result.substring(0,result.length()-2);

}

13

Page 14: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

32. The format specifier for a floating point number can also take the width (number of columns) of the space to print the number:

% width . decimals f

33. Example – The code below specifies a field width of 8 with 2 decimal places:

Code Output

double x = 498.57334;result = String.format("%8.2f", x);System.out.println(result);

Notes:a. You can also use a “-“ flag in front of the width to left-justifyb. If the specified field width is not wide enough, The JVM just expands it so that the whole number is

displayed.

34. 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(int i=0; i<vals.length; i++) {

System.out.printf("%6.2f\n", vals[i]);}

498.57 4.33 27.92

Homework:

23. 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: Jed, age:22, salary: $48,339.23Name: Keisha, age:33, salary: $68,992.92Name: Jaylen, age:44, salary: $121,042.04

24. Write a method, formatWeights that 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:

42.335 67.284 92.384 442.304 73.888

35. 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.

14

Page 15: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

15

Page 16: Valdosta State University · Web viewthat accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case. 4.4.8 – Strings 3 – Substring

36. Example:

Code Output

double x = 498.57334;double y = 6.1945;System.out.printf("x=%8.2f\ny=%8.2f", x, y);

x= 498.57y= 6.19

16