2014-12-06 26 views
-3
In my program a string is generated like this: Energie 670 kJ/160 kcal 
So how to write split function in java code and the first keyword Energie should print 
the outputs? 

輸入:嗨..如何編寫java代碼來分割字符串?

   Energie 670 kJ/160 kcal 

預期輸出:

   1) Energie 670 kJ 

      2) Energie 160 kcal 

如果任何人有一個解決這個問題,或者要去約拆分 字符串更好的辦法兩次?

在此先感謝

+0

你知道這是一個'String',並且你想對它做一些操作。閱讀API:https://docs.oracle.com/javase/7/docs/api/java/lang/String.html。這樣你就可以學到更多東西。 Stackoverflow不能替代API文檔。 – toddlermenot 2014-12-06 06:36:14

回答

1

有方法在String類爲它

String[] split(String delimiter) 

使用這樣

String strs[] = str.split("/"); 
for (int i=0; i<strs.length; i++) { 
    System.out.println(strs[i].trim()); 
} 

但正如其他人所說,獲得舒適的閱讀API,最你可能會找到你正在尋找的東西。

1

嘗試此使用split API字符串對象,如下:

String str = "Energie 670 kJ/160 kcal"; 
String strs[] = str.split("/");//if you are expecting multiple space/tab etc use "\\s+/\\s+ instead of "/"" 
for (int i=0; i<strs.length; i++) { 
    System.out.println(strs[i]); 
} 
0
String s = "Energie 670 kJ/160 kcal"; 
// remove the leading "Energie" 
String stripped = s.replace("Energie", "").trim(); 
String[] parts = stripped.split("/"); 
// take what's left of the slash 
String s1 = "Energie ".concat(parts[0].trim()); 
// take what's right of the slash 
String s2 = "Energie ".concat(parts[1].trim()); 
// print both resultant strings 
System.out.println(s1); 
System.out.println(s2); 
0
public class StringSplit { 
public static void main(String args[]) throws Exception{ 
String testString = "670 kJ/160 kcal"; 

System.out.println 
    (java.util.Arrays.toString(testString.split("\\s+"))); 

} }

output : [670,kJ,/,160,kcal] 

獲得從陣列reqiuered值。您也可以使用'\'拆分字符串,而不是使用空格。

1

您可以使用適當的方法string.split()來分割字符串。

String string =「Energie 670 kJ/160 kcal」;

String [] parts = string.split(「/」);

String part1 = parts [0] .trim(); // Energie 670 kJ

String part2 = parts [1] .trim(); // 160 kcal

+0

在第二部分中,我應該得到這樣的輸出:Energie 160 kcal – 2014-12-07 13:51:48