0

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++)
2
  • You can also instantiate the string array right away. String[] stateArray = new String[]{"Alabama", "Alaska", "and the rest"}; Commented Mar 13, 2013 at 0:33
  • you don't have spaces around ^ don't use it in split. Commented Mar 13, 2013 at 12:49

2 Answers 2

5

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("\\^");
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.