Split StringBuffer based on characters
Hi,
Yes, this is another simple String question. I read the API for String and StringBuffer, but I'm not sure how to do this. Basically, I want to take a StringBuffer, such as "Bar of foo" and break it into three separate words, according to the spaces, and add those words to an ArrayList.
So, in the above example, I want to break "Bar of foo" up into "Bar", "of", and "foo", and create an ArrayList with the contents: ["Bar", "of", "foo"].
Is this possible? If so, how could I do it? Is there something in the API I missed?
Thanks,
Dan
[578 byte] By [
Djaunla] at [2007-10-3 3:48:33]

> If you don't care what type of list then the code is
> simply:
> List list = Arrays.asList("Bar of
> foo".split("\\s"));
Yes! Much better. I need to use Arrays much more than I do! One can take it a step further with
List<String> list = (List<String>)Arrays.asList(value.split("\\s"));
Thanks for the help everyone. I knew of the split method, but I was unsure as to what it does. I used the method of splitting the string into an array, then iterating through the array and adding each element to an ArrayList, because I am more familar with it.
I do have a question regarding this:
List<String> list = (List<String>)Arrays.asList(value.split("\\s"));
I've never understood this: what does the (List<String>)
signify? I have never understood the whole concept of putting things in parentheses like that. What does it mean? Is there a tutorial somewhere on this?
Thanks for the help,
Dan
Sometimes you know what a type is but the compiler doesn't so you cast it to the type you know it is. Or to tell the compiler it is okay to convert a primative type that would result in a loss of precision.
Example:
List<String> list = new LinkedList<String>();
String last = list.getLast();
The above code results in a compiler error even though list is really a LinkedList(). List does not have the getLast() method but LinkedList does. So you can tell the compiler that it is safe to use list as a LinkedList.
String last = ((LinkedList<String>)list).getLast();
Another example:
double d = 1.1;
int a = d * 9;
double b = a/10;
The above code also causes a compiler error. Fixed by changing type casting the double to an int, but we loose the 0.1 of the 1.1.
int a = (int)d * 10;
Now the value for b will be 0 and not 0.9 unless again you type cast either a or 10 to a double.
double d = 1.1;
int a = (int)d * 9;
double b = (double)a / 10;
You can probably find better examples and a better explanation by searching google for: java type casting