如何將字串拆分為多個子字串?



問題描述

如何將字串拆分為多個子字串?

解決方案

以下示例使用 str split(string) 方法將字串拆分為多個子字串,然後列印這些子字串。

public class JavaStringSplitEmp{
   public static void main(String args[]) {
      String str = "jan-feb-march";
      String[] temp;
      String delimeter = "-";
      temp = str.split(delimeter);
      
      for(int i = 0; i < temp.length; i++) {
         System.out.println(temp[i]);
         System.out.println("");
         str = "jan.feb.march";
         delimeter = "\\.";
         temp = str.split(delimeter);
      }
      for(int i = 0; i < temp.length; i++) {
         System.out.println(temp[i]);
         System.out.println("");
         temp = str.split(delimeter,2);
         
         for(int j = 0; j < temp.length; j++){
            System.out.println(temp[j]);
         }
      }
   }
}

結果

上述程式碼示例將產生以下結果。

jan

feb

march

jan

jan
feb.march
feb.march

jan
feb.march

這是一個字串拆分的另一個示例

public class HelloWorld {
   public static void main(String args[]) {
      String s1 = "t u t o r i a l s"; 
      String[] words = s1.split("\\s"); 
      for(String w:words) {
         System.out.println(w);  
      }  
   }
}

結果

上述程式碼示例將產生以下結果。

t 
u 
t 
o 
r 
i 
a 
l 
s 
java_strings.htm
廣告
© . All rights reserved.