選單

Java 中基本字串操作概述

目錄

分割字串 –

此操作使用特定分隔符號分割字串。

範例程式碼

public static void splitSample() {
    String line = "りんご,みかん,バナナ";
    String[] fruits = line.split(",");
    for (String fruit : fruits) {
        System.out.println(fruit);
    }
}

輸出結果:

蘋果、玉米、香蕉

基本字串連接

您可以使用“+”運算符連接字串。

範例程式碼

public static void plusSample() { String s1 = "hello "; String s2 = "world!"; System.out.println(s1 + s2); }

輸出結果:

你好世界!


使用分隔符號連接字串。 主題:

此函數使用特定分隔符號連接字串(Java 8 及更高版本可用)。

範例程式碼

public static void joinSample() {
    String line = String.join(",", "りんご", "みかん", "バナナ");
    System.out.println(line);
}

連接運算子也可以用同樣的方法連接字串陣列。

public static void joinArraySample() {
    String[] fruits = {"りんご", "みかん", "バナナ"};
    String line = String.join(",", fruits);
    System.out.println(line); //結果は同じ
}

輸出結果:

蘋果、柳橙、香蕉

從指定範圍內提取字串。 子字串

您可以指定提取的起始點和結束點,並提取字串的一部分。

範例程式碼

public static void substringSample() {
    String str = "hello world!";
    System.out.println(str.substring(0, 5));
    System.out.println(str.substring(2, 9));
    System.out.println(str.substring(6)); //始点だけ指定することもできる
}

輸出結果:

你好,世界!

刪除開頭和結尾的空格。 修剪

刪除字串開頭和結尾的空格、換行符和製表符。
字串中的空白字元和全角空格不會被刪除。

範例程式碼

public static void trimSample() { String str = " hello world!"; System.out.println(str.trim()); }

輸出結果:

你好世界!

將字串的一部分替換為另一個字串。 代替

此函數將字串的一部分替換為指定的字串。 `replace` 會取代所有符合的字串。

範例程式碼

public static void replaceSample() {
    String str = "hello world!";
    System.out.println(str.replace("l", "×"));
}

輸出結果:

he××o wor×d!

`replaceFirst` 只會取代第一個符合的字串。

範例程式碼

public static void replaceFirstSample() { String str = "hello world!"; System.out.println(str.replaceFirst("l", "×")); }

輸出結果:

你好世界!

傳回字串中的字元數。 尺寸

文字列の文字数を返します。String.length()は単純に文字数を返します。

範例程式碼

public static void lengthSample() {
    String str = "〇〇県□□市△△町10-11";
    System.out.println(str.length());
}

輸出結果:

14

若要取得位元組數,請使用 String.getBytes().length。由於 Java 8 使用 UTF-8 作為預設字元編碼,因此每個全角字元佔用 3 個位元組。

範例程式碼

public static void byteLengthSample() { String str = "〇〇 府 □□ 市 △△ 鎮 10-11"; System.out.println(str.getBytes().length); }

輸出結果:

32
  • 網址をコピーしました!
目錄