Peter Alpha
Peter Alpha

Reputation: 25

Populating a string array using a string? (JAVA)

I was looking around the site for some similar answers but I haven't found anything so far. I am wondering how I can populate a string array with a pre-established string. Also, if I have a separate class, would I include this code in a method or in a constructor?

The string:

String stateList = "Alabama^Alaska^Arizona^Arkansas^California^Colorado^Connecticut^Delaware^Florida^"
            + "Georgia^Hawaii^Idaho^Illinois^Indiana^Iowa^Kansas^Kentucky^Louisiana^Maine^Maryland^"
            + "Massachusetts^Michigan^Minnesota^Mississippi^Missouri^Montana^Nebraska^Nevada^"
            + "New Hampshire^New Jersey^New Mexico^New York^North Carolina^North Dakota^Ohio^Oklahoma^"
            + "Oregon^Pennsylvania^Rhode Island^South Carolina^South Dakota^Tennessee^Texas^Utah^"
            + "Vermont^Virginia^Washington^West Virginia^Wisconsin^Wyoming";

My attempt (which did not work):

String[] stateArray = stateList.split(" ^ ");
    for(int i=0; i < stateArray.length; i++)

Upvotes: 0

Views: 346

Answers (2)

rgettman
rgettman

Reputation: 178263

The ^ character has special meanings in regular expressions; provide a backslash character (which itself needs to be escaped in Java), so that split interprets it as a literal ^:

String[] stateArray = stateList.split("\\^");

Upvotes: 5

Pshemo
Pshemo

Reputation: 124225

Try using split.("\\^"). This method uses regex, and ^ in regex have special meaning (which in this case is start of input data). To escape it you need to pass \^ to regex engine, so you will need to use \\^ form.

Upvotes: 2

Related Questions