简体   繁体   中英

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!

The Java Documentation is your friend:

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

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

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

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

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);
}

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM