Section 8 The String Class
|
Suppose that s1, s2, s3, and s4 are four strings, given as follows:
String s1 = "Welcome to Java";
String s2 = s1;
String s3 = new String("Welcome to Java");
String s4 = s3.intern();
What are the results of the following expressions?
(1)A s1 == s2
(2) s1 == s3
(4) s2.equals(s3)
(5) s1.compareTo(s2) (15) s1.substring(5, 11)
(6) s2.compareTo(s3) (16) s1.startsWith("Wel")
(7) s1 == s4 (17) s1.endsWith("Java")
(8) s1.charAt(0) (18) s1.toLowerCase()
(9)A s1.indexOf('j') (19) s1.toUpperCase()
(10) s1.indexOf("to") (20) " Welcome ".trim()
(11) s1.lastIndexOf('a') (21) A s1.replace('o', 'T')
(12) s1.lastIndexOf("o", 15) (22) s1.replaceAll("o", "T")
(13) s1.length() (23) s1.replaceFirst("o", "T")
(14)A s1.substring(5) (24) s1.toCharArray()
|
|
(Occurrences of a specified character) Write a method that finds the number of occurrences of a specified character in the string using the following header:
public static int count(String str, char a)
For example, count("Welcome", 'e') returns 2.
|
|
(Counting the letters in a string) Write a method that counts the number of letters in the string using the following header:
public static int countLetters(String s)
Write a main method to invoke countLetters("Java in 2008") and display its return value.
|
|
(Binary to decimal) Write a method that parses a binary number as a string into a decimal integer. The method header is as follows:
public static int parseBinary(String binaryString)
For example, binaryString 10001 is 17 (1 x 24 + 0 x 23 + 0 x 22 + 0 x 2 + 1 = 17) So, parseBinary("10001") returns 17. Use binary string 11111111 to test the method. Note that Integer.parseInt("10001", 2) parses a binary string to a decimal value. Do not use this method in this exercise.
|
Solutions
8.1 (1) True
8.1 (3) True
8.1 (9) -1
8.1 (14) me to Java
8.1 (21) WelcTme tT Java
Solutions for 8.4 is provided by shah. Click on comments section.
8.6
4 comments:
String class exercise
8.4
/**
* @(#)shah.java
*
* shah application
*
* @author
* @version 1.00 2010/10/13
*/
public class shah {
public static void main(String[] args) {
// TODO, add your application code
System.out.println(count("Hello World!",'r');
}
public static int count(String str,char a) {
int long_string = str.length();
int i, countchar=0;
for(i=0;i<long_string;i++)
{
if ((str.charAt(i)==a))
countchar++;
}
return (countchar);
}
}
hey, did u ever find the solution for 8.6? i know this was 4 years ago, but i have the same problem now? haha any help please?
Hi Zinnia Islam. InsyaAllah.. i will try to code the program, anyway- why are u interested question 8.6?
I have added solution for 8.6. Couldn't post the code since it will be 'corrupted' by Blogger :)
Post a Comment