用於拆分和連線字串的 Java 程式


要拆分和連線 Java 中的字串,請使用 split() 和 join() 方法,如下例所示 −

示例

public class Demo{
   public static void main(String args[]){
      String my_str = "This_is_a_sample";
      String[] split_str = my_str.split("_", 4);
      System.out.println("The split string is:");
      for (String every_Str : split_str)
      System.out.println(every_Str);
      String joined_str = String.join("_", "This", "is", "a", "sample");
      System.out.println("The joined string is:");
      System.out.println(joined_str);
   }
}

輸出

The split string is:
This
is
a
sample
The joined string is:
This_is_a_sample

一個名為 Demo 的類包含 main 函式。這裡,定義了一個 String 物件並根據“_”值將它拆分到最後一個單詞。反覆執行“for”迴圈,並根據“_”值拆分該字串。再次,使用“join”函式連線字串。相關的訊息將顯示在控制檯上。

更新於: 07-Jul-2020

4K+ 瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.