Linkedin Java 檢定題庫 substring


Posted by c9103205 on 2021-07-05

似乎很喜歡考substring 將所有相關題目彙整在一起

String str = "abcde";
str.trim();
str.toUpperCase();
str.substring(3, 4);
System.out.println(str);
  1. CD
  2. CDE
  3. D
  4. "abcde"

Answer : 4
解析: 這題表面上看起來是在考substring,但其實是一題陷阱題。
題目 2,3,4 行,雖然都對字串做了一些操作,但是如果要記錄操作完的過程
則必須像下面這樣寫
str = str.trim();
str = str.toUpperCase();
str = str.substring(3, 4);
不然其實str中的字串沒有任何改變

Given the string "strawberries" saved in a variable called fruit, what would fruit.substring(2, 5) return?

  1. rawb
  2. raw
  3. awb
  4. traw

answer :2
解析:substring(2, 5) 表示從index 2 切到5的前一個(不包括5),也就是切
2,3,4
注意字串的index是從0開始算,所以這題答案是"raw"

class Main {
    public static void main (String[] args) {
        String message = "Hello world!";
        String newMessage = message.substring(6, 12)
            + message.substring(12, 6);
        System.out.println(newMessage);
    }
}
  1. The code does not compile.
  2. A runtime exception is thrown.
  3. "world!!world"
  4. "world!world!"

answer : B

解析:
substring 只能從前面切到後面,沒辦法從後面切回來
所以執行後會報 java.lang.StringIndexOutOfBoundsException


#java #linkedin







Related Posts

Checked and Unchecked Exception in Java

Checked and Unchecked Exception in Java

Print one to nine

Print one to nine

什麼是 Command Line (CLI)?

什麼是 Command Line (CLI)?


Comments