d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Break A String Into An Array Of Strings > Using Scanner In Java
Add Reply New Topic New Poll
Member
Posts: 29,374
Joined: Mar 27 2008
Gold: 504.69
Oct 18 2015 08:12am
Stuck on this part in an assignment I have. What I have so far is,

Code


import java.util.*
...
public void setArray()
{
String input;
Scanner scan = new Scanner(System.in);

input = scan.nextLine();

}


Prof told me there is a way I can feed scanner my string and it will create an array of strings for me. Any help appreciated.
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Oct 18 2015 10:52am
String should have a split(..) method where you can break a string into an array of strings by some delimiter. personally i dont have much experience with scanner, but you could look up the docs for it
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Member
Posts: 23,862
Joined: Aug 16 2006
Gold: 20.00
Oct 18 2015 11:14am
pretty sure there was a way to tokenize shit with scanner. Might want to look into that
Member
Posts: 2,757
Joined: Nov 26 2007
Gold: 1,214.81
Oct 18 2015 12:25pm
use String.split("")

Code
String[] tokens = input.split("");


You can replace the argument with a regex or any char to split by. For example, you can split by spaces by putting " " in the arguments, so "Hello World" would become {"Hello","World"}


This post was edited by labatymo on Oct 18 2015 12:27pm
Member
Posts: 29,374
Joined: Mar 27 2008
Gold: 504.69
Oct 18 2015 02:38pm
Thanks everyone.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll