String字串常用方法

字串常用方法

開頭,結尾,包含

1
2
3
4
5
6
7
8
9
10
  String s1 = "Hello World";
  // 是否以Hel開頭的?
  boolean isStart = s1.startsWith("Hel");
  System.out.println(isStart);
  // 是否以Hel結尾的?
  boolean isEnd = s1.endsWith("Hel");
  System.out.println(isEnd);
  // 是否包含abc
  boolean isContain = s1.contains("abc");
  System.out.println(isContain);
true
false
false

尋找字串

1
2
3
4
5
6
7
8
9
10
  String s1 = "Hello World";
  // 查詢參數在字串中第一次出現的位置,索引值從0開始數
  int position1 = s1.indexOf("ol");
  System.out.println(position1);
  // 從指定的位置開始找
  position1 = s1.indexOf("o", 6);
  System.out.println(position1);
  // 字串最後出現的位置
  position1 = s1.lastIndexOf("ol");
  System.out.println(position1);
3
7
3

取得字串中的子字串

取得索引大於等於 >= x,小於 < y。
不包含y。
語法

substring(x, y)
x <= 索引 < y

程式碼

1
2
3
4
5
6
7
  String s1 = "Hello World";
  // 取得字串中的子字串
  String str4 = s1.substring(2);
  System.out.println(str4);
  // 取得位置2到6的字元,不包含6
  str4 = s1.substring(2, 6);
  System.out.println(str4);
llo World
llo 

去掉字串前後

1
2
3
  // trim去掉前後空格
  String str5 = "  Hello World!   ".trim();
  System.out.println(str5);
Hello World!

字串轉基本類型

int基本類型包了一個殼,就變成類別Interger,就可以使用類別的方法,如Interger.parseInt()字串變成數字

1
2
3
4
5
6
7
8
9
10
  // 字串轉基本類型
  // 轉int
  int i = Integer.parseInt("12345");
  System.out.println(i);
  // 轉double
  double d = Double.parseDouble("12.55");
  System.out.println(d);
  // 基本類型轉字串
  System.out.println(String.valueOf(i));
  System.out.println(String.valueOf(d));
12345
12.55
12345
12.55

results matching ""

    No results matching ""