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>开发者_如何学Python 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(" ");
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
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);
}
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+")));
精彩评论