Splitting a string up in java as it is pulled from a list?
I'm looking to split a List of Strings up as i iterate throught the list imagine the following as the List.
["StringA.StringB.StringC"]["StringA.StringB.StringC"]["StringA.StringB.StringC"]["StringA.StringB.StringC"]
So i want 开发者_如何转开发to iterate through the list pull out each string ("StringA.StringB.StringC"
)
Then want to seperate by the "."
and assign StringA to a String variable - String B to one and String C. Perform some work and move on to the next.
Any ideas how i can do this?
This is a fairly simple task. Just use a foreach to iterate through the list, and then split the string on the .
character.
for(String s: list) {
String[] splitString = s.Split("\\.");
// do work on the 3 items in splitString
}
The variable splitString
will have a length of 3.
Of course! You just want String#split()
.
for (String s : myList)
{
String[] tokens = s.split("\\.");
// now, do something with tokens
}
You need to escape the period in the argument to split()
because the string is interpreted as a regex pattern, and an unescaped period ("."
) will match any character - not what you want!
So you have a list of String[] which are concatenated strings. Unless this is some sort of legacy data structure, you might do better to make this more uniform in some way.
In any case, iteration is pretty straightforward -
List<String[]> l = ....
for (String[] outer: l) {
for (String s: outer){
for (String inner: s.split("\\.")) // s.split takes a regex and returns a String[],
// inner has your inner values now
To iterate through a list, see http://download.oracle.com/javase/tutorial/java/nutsandbolts/for.html
To split a string, use String.split(regex)
.
The String class has the split(String regex)
method, which splits the string by regular expression. If you don't want the hassle of dealing with regular expressions, you can use the very handy StringUtils class from Apache Commons Lang.
List<String> strings=new ArrayList<String>();
for (String s:stringList){
strings.addAll(Arrays.asList(s.split("\\.")));
}
then you'll have all the strings in one list and you can iterate over them.
精彩评论