-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?

Input :

              Energie 670 kJ / 160 kcal

Expected output :

             1) Energie 670 kJ

             2) Energie 160 kcal

If anyone have a solution to this problem or better way of going about splitting a string twice?

Thanks in advance

Praveen Kumar K R
  • 1,762
  • 2
  • 11
  • 7
  • You know it is a `String` and you want some operation done on it. Read the API: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html. That way you would learn this and more. Stackoverflow is no substitute for API documentation. – toddlermenot Dec 06 '14 at 06:36

5 Answers5

1

There is method in the String class for it

String[] split(String delimiter)

Use like this

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

But as others mentioned ,get comfortable reading the API ,most of the time you're likely to find what you are looking for .

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
Sainath S.R
  • 3,074
  • 9
  • 41
  • 72
1

Try this using split api of String object as below:

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]);
}
SMA
  • 36,381
  • 8
  • 49
  • 73
1

You can use appropriate method string.split() to split the string.

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

Community
  • 1
  • 1
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);
Aaron Hammond
  • 617
  • 4
  • 9
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]

Get the reqiuered value from array. Instead of using whitespace you can also use '\' to split the string.

manDroid
  • 1,125
  • 3
  • 13
  • 25