user721588
user721588

Reputation:

how to print part of a string in Java

CODE:

InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
String input = in.readLine();
ArrayList<String> massiiv = new ArrayList();
for (int i = 0; i < input.length(); i++)
   massiiv.add(input[i]); // error here

HI!

How can I split the input and add the input to the data structure massiiv?

For instance, input is: "Where do you live?". Then the massiiv show be:

massiv[0] = where
massiv[1] = do
massiv[2] = you

THANKS!

Upvotes: 0

Views: 5601

Answers (6)

Jiri Kriz
Jiri Kriz

Reputation: 9292

A one-line solution. Any amount of whitespace possible between the strings.

ArrayList<String> massiiv =  new ArrayList(Arrays.asList(input.split("\\s+")));

Upvotes: 0

Sahil Muthoo
Sahil Muthoo

Reputation: 12496

Try using split(String regex).

String[] inputs = in.readLine().split(" "); //split string into array
ArrayList<String> massiiv = new ArrayList();
for (String input : inputs) {
    massiiv.add(inputs);
}

Upvotes: 1

Ryan Gross
Ryan Gross

Reputation: 6515

You would use the string.split() method in java. In your case, you want to split on spaces in the string, so your code would be:

massiiv = new ArrayList(input.split(" "));

If you don't want to have the word you in your output, you would have to do additional processing.

Upvotes: 0

Simone
Simone

Reputation: 2311

InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
String input = in.readLine();

String[] massiiv = input.split(" ");

Upvotes: 2

DaveFar
DaveFar

Reputation: 7457

Use a StringTokenizer, which allows an application to break a string into tokens.

Use space as delimiter, set the returnDelims flag to false such that space only serves to separate tokens. Then

     StringTokenizer st = new StringTokenizer("this is a test");
     while (st.hasMoreTokens()) {
         System.out.println(st.nextToken());
     }

prints the following output:

     this
     is
     a
     test

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76908

The Java Documentation is your friend:

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

String[] myWords = input.split(" ");

Upvotes: 3

Related Questions