Documentation

The Java™ Tutorials
Hide TOC
Questions and Exercises问题和练习
Trail: Learning the Java Language
Lesson: Numbers and Strings

Questions and Exercises: Characters and Strings问题和练习:字符和字符串

Questions

  1. What is the initial capacity of the following string builder?以下字符串生成器的初始容量是多少?

    StringBuilder sb = new StringBuilder("Able was I ere I saw Elba.");
  2. Consider the following string:考虑以下字符串:

    String hannah = "Did Hannah see bees? Hannah did.";
    1. What is the value displayed by the expression hannah.length()?表达式hannah.length()显示的值是多少?

    2. What is the value returned by the method call hannah.charAt(12)?方法调用hannah.charAt(12)返回的值是多少?

    3. Write an expression that refers to the letter b in the string referred to by hannah.写一个表达式,引用hannah引用的字符串中的字母b

  3. How long is the string returned by the following expression?以下表达式返回的字符串有多长?What is the string?绳子是什么?

    "Was it a car or a cat I saw?".substring(9, 12)
  4. In the following program, called ComputeResult, what is the value of result after each numbered line executes?在以下名为ComputeResult的程序中,执行每个编号行后的result值是多少?

    public class ComputeResult {
        public static void main(String[] args) {
            String original = "software";
            StringBuilder result = new StringBuilder("hi");
            int index = original.indexOf('a');
    
    /*1*/   result.setCharAt(0, original.charAt(0));
    /*2*/   result.setCharAt(1, original.charAt(original.length()-1));
    /*3*/   result.insert(1, original.charAt(4));
    /*4*/   result.append(original.substring(1,4));
    /*5*/   result.insert(3, (original.substring(index, index+2) + " ")); 
    
            System.out.println(result);
        }
    }

Exercises练习

  1. Show two ways to concatenate the following two strings together to get the string "Hi, mom.":显示将以下两个字符串连接在一起以获得字符串"Hi, mom."的两种方法:

    String hi = "Hi, ";
    String mom = "mom.";
  2. Write a program that computes your initials from your full name and displays them.编写一个程序,根据您的全名计算您的姓名首字母并显示它们。

  3. An anagram is a word or a phrase made by transposing the letters of another word or phrase; for example, "parliament" is an anagram of "partial men," and "software" is an anagram of "swear oft".字谜是将另一个单词或短语的字母转置而成的单词或短语;例如,“parliament”是一个“partial men”的字谜,“software”是一个“swear oft”的字谜。Write a program that figures out whether one string is an anagram of another string.编写一个程序,计算一个字符串是否是另一个字符串的字谜。The program should ignore white space and punctuation.程序应该忽略空格和标点符号。

Check your answers.检查你的答案。


Previous page: Autoboxing and Unboxing
Next page: Generics (Updated)