Jeremy Zhang
Jeremy Zhang

Reputation: 13

Split a string in Java and picking up a part of it

Say I got a string from a text file like

"Yes ABC 123

Yes DEF 456

Yes GHI 789"

I use this code to split the string by whitespace.

while (inputFile.hasNext())
  {
     String stuff = inputFile.nextLine();

     String[] tokens = stuff.split(" ");

     for (String s : tokens)
     System.out.println(s);
  }

But I also want to assign Yes to a boolean, ABC to another string, 123 to a int. How can I pick them up separately? Thank you!

Upvotes: 0

Views: 176

Answers (4)

Prateek
Prateek

Reputation: 1926

If your input String is going to be in the same format always i.e. boolean,String ,int then you can access the individual indices of token array and convert them to your specified format

boolean opinion = tokens[0].equalsIgnoreCase("yes");
String temp = token[1];
int i = Integer.parseInt(token[2])

But you might require to create an array or something that stores the values for consecutive inputs that user does otherwise these variables would be over ridden for every new input from user.

Upvotes: 0

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

Create Class Line and List<Line> that will store all your file into list:

public class Line{

private boolean mFlag = false;
private int  mNum = 0;
private String  mStr;

public Line(String stuff) {
    String[] tokens = stuff.split("[ ]+");

    if(tokens.length ==3){
        mFlag=tokens[0].equalsIgnoreCase("yes");
        mNum=Integer.parseInt(tokens[1]);
        mStr=tokens[3];
    }
}
}

and call it:

public static void main(String[] args) {

 List<Line> list = new ArrayList<Line>(); 
 Line line;

 while (inputFile.hasNext())
 {
  String stuff = inputFile.nextLine();

  line = new Line(stuff);

  list.add(line);
 }
}

Upvotes: 0

user2511414
user2511414

Reputation:

boolean b=tokens[0].equalsIgnoreCase("yes");
String name=tokens[1];
int i=Integer.parseInt(tokens[2]);

Upvotes: 1

Sebastiaan van den Broek
Sebastiaan van den Broek

Reputation: 6331

Could you clarify what the exact purpose of what you're doing is? You can refer to the separate Strings with tokens[i] with i being the index. You could throw these into a switch statement (since Java 7) and match for the words you're looking for. Then you can take further action, i.e. convert the Strings to Booleans or Ints.

You should consider checking the input to be valid too even if you are expecting the file to always have those 3 words separated by a space.

Upvotes: 0

Related Questions