user297850
user297850

Reputation: 8015

How to split a string and extract specific elements?

I have a file, which consists of lines such as

20 19:0.26 85:0.36 1064:0.236 # 750

I have been able to read it line by line and output it to the console. However, what I really need is to extract the elements like "19:0.26" "85:0.36" from each line, and perform certain operations on them. How to split the lines and get the elements that I want.

Upvotes: 0

Views: 1124

Answers (4)

dsingleton
dsingleton

Reputation: 1006

Java Strings have a split method that you can call

String [] stringArray = "some string".split(" ");

You can use a Regular expression if you want to so that you can match certain characters to split off of.

String Doc: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

Pattern Doc (Used to make regular expressions): http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

Upvotes: 0

Aerrow
Aerrow

Reputation: 12134

Modify this code as per yours,

public class JavaStringSplitExample{

  public static void main(String args[]){

  String str = "one-two-three";
  String[] temp;

  /* delimiter */
  String delimiter = "-";
  /* given string will be split by the argument delimiter provided. */
  temp = str.split(delimiter);
  /* print substrings */
  for(int i =0; i < temp.length ; i++)
    System.out.println(temp[i]);

  /*
  IMPORTANT : Some special characters need to be escaped while providing them as
  delimiters like "." and "|".
  */

  System.out.println("");
  str = "one.two.three";
  delimiter = "\\.";
  temp = str.split(delimiter);
  for(int i =0; i < temp.length ; i++)
    System.out.println(temp[i]);

  /*
  Using second argument in the String.split() method, we can control the maximum
  number of substrings generated by splitting a string.
  */

  System.out.println("");
  temp = str.split(delimiter,2);
  for(int i =0; i < temp.length ; i++)
    System.out.println(temp[i]);

  }

}

Upvotes: 0

Stephen P
Stephen P

Reputation: 14810

Parsing a line of data depends heavily on what the data is like and how consistent it is. Purely from your example data and the "elements like" that you mention, this could be as easy as

String[] parts = line.split(" ");

Upvotes: 0

Roman
Roman

Reputation: 66196

Use a regular expression:

Pattern.compile("\\d+:\\d+\\.\\d+");

Then you can create a Matcher object from this pattern end use its method find().

Upvotes: 2

Related Questions