1 字符串

StringBuilder由于是非线程安全的,所以效率高一点String类是immutable,所以执行+=可能带来效率问题 ```java import java.util.*;
public class StringAndStringBuffer {
public static void main(String args[]) {String a = "1";String s = "";StringBuffer sb = new StringBuffer();final int N = 10000;long t0 = System.currentTimeMillis();for (int i = 0; i < N; ++i)s += a;long t1 = System.currentTimeMillis();for (int i = 0; i < N; ++i)sb.append(a);long t2 = System.currentTimeMillis();System.out.println(t1 - t0);System.out.println(t2 - t1);}
}
> 在 Java 中, `String` 的 `+=` 被翻译为:先将 `String` 转换为 `StringBuilder` 对象,然后执行 `append()` ,最后执行 `toString()` 转化回 `String`<a name="levIR"></a>## 1.1 String 常用方法【**返回新的 **`**String**`** 对象**】- **连接 **`**concat()**`** **- **替换 **`**replace()**`** **- **替换全部 **`**replaceAll()**`** **- **返回子串 **`**substring()**`** **- **转化为小写 **`**toLowerCase()**`** **- **转化为大写 **`**toUpperCase()**`** **- **去掉空格 **`**trim()**`** **- **转换为字符串 **`**toString()**`** ****【查找】**- `**endsWith()**`** **- `**startsWith()**`** **- `**indexOf()**`** **- `**lastIndexOf()**`** ****【比较】**- `**equals()**`** **- `**equalsIgnoreCase()**`** **- `**compareTo()**`**【字符以及长度】**- `**charAt()**`** **- `**length()**`** ****【格式化】**- `**format()**`** **<br /><a name="izKoK"></a>## 1.2 字符串常量(interned)<a name="JT6Ta"></a>## 1.3 StringBuffer 类> `String` 的这些方法都会返回一个 `new` 的对象,而 `StringBuffer` 不会, `StringBuffer` 更像是 C++ 中的容器。<a name="42INY"></a>## 1.4 字符串的分割```javaimport java.util.*class TestStringTokenizer {public static void main(String[] args) {StringTokenizerst = new StringTokenizer("this is a test", " ");while (st.hasMoreTokens()) {System.out.println(st.nextToken());}st = new StringTokenizer("253,197,546", ",");double num = 0;while (st.hasMoreTokens()) {sum += Double.parseDouble(st.nextToken());}System.out.println(sum);}}
2 日期与时间
- 日期格式化
System.currentTimeMillis()可以获取时间戳,单位是秒Long.parseLong(string)可以将 String 中的长整型提取出来 ```java package com.lht.date;
import java.text.SimpleDateFormat; import java.util.Date;
public class CookieServlet extends HttpServlet { public static void main() { // Date date = new Date(); // 无参默认创建当前时间的 Date 对象 String now = System.currentTimeMillis() + “”; // 获取当前时间戳并转换成字符串 Date date = new Date(Long.parseLong(now)); SimpleDateFormat f = new SimpleDateFormat(“yyyy 年 MM 月 dd 日 E HH 点 mm 分 ss 秒”); System.out.println(f.format(date)); } }
```java今天是 2022 年 7 月 16 日 星期六 20 点 50 分 23 秒
