String s1 = "Hello World"; // 常量池中創建/復用
String s2 = new String("Hello World"); // 堆中創建新對象
| 功能 | 方法 | 說明 |
|---|---|---|
| 連接 | + / concat() | 生成新字符串,原對象不變 |
| 長度 | length() | 返回字符數 |
| 截取 | substring(begin, end) | 左閉右開 [begin, end) |
| 查找索引 | indexOf(str) / lastIndexOf(str) | 首次/最後一次出現位置,無則 -1 |
| 去空格 | trim() | 僅移除首尾空白字符 |
| 替換 | replace(old, new) | 替換所有匹配子串 |
| 比較 | equals(obj) | 嚴格區分大小寫比較內容 |
| 前綴/後綴 | startsWith/endsWith(prefix) | 判斷開頭/結尾 |
| 大小寫轉換 | toLowerCase()/toUpperCase() | 返回新字符串 |
| 分割 | split(regex) | 按正則表達式分割為數組 |
隨機生成 4 位驗證碼
public static void main(String[] args) {
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
int idx = (int)(Math.random() * chars.length());
sb.append(chars.charAt(idx));
}
System.out.println(sb);
}
解析 XML 片段提取姓名/性別
String xml = ""; String name = xml.substring(xml.indexOf(" 張三 男 ")+4, xml.indexOf(" ")); String gender = xml.substring(xml.indexOf("")+4, xml.indexOf(" ")); System.out.println("姓名:" + name + " 性別:" + gender);
Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); // 0-11 int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); // 24制 int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); int milli = cal.get(Calendar.MILLISECOND);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String formatted = sdf.format(cal.getTime()); // 注意:需轉為 Date
System.out.println(formatted);
常用模式字母:y年 M月 d日 H時(24) h時(12) m分 s秒 S毫秒
cal.set(2002, 2, 13); // 年、月(0-based)、日 cal.set(2002, 2, 13, 18, 55, 32); // 含時分秒 cal.set(Calendar.YEAR, 1980); // 單獨設置字段
Calendar cal = Calendar.getInstance();
cal.set(2002, 2, 13);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
System.out.println(sdf.format(cal.getTime()));
// 輸出:2002年03月13日 00:00:00 (時分秒默認當前時間)