0

Eg if I have a string "{1,2,3,4,5}" I would like to get an int[] object from that string.

I have looked a bit at Janino and Beanshell, but can't seem to find the correct way to get them to do this for me.

I am looking for a generic solution, one that works for all types - not only integer arrays.

8
  • What is the format of the string? JSON? toString? Commented Jun 18, 2012 at 10:35
  • Just a normal Java string containing something like "{1,2,3}", "1", "Stackoverflow" and so forth. Commented Jun 18, 2012 at 10:37
  • 1
    That's a different question, since now you're asking about converting an essentially arbitrary string into, apparently, arbitrary Java objects. What are you really trying to do? Commented Jun 18, 2012 at 10:38
  • I am trying to create objects based on what a user types in a field. So if a user types {1,2,3}, I want an int array. If the user types Hello, I want a string. Commented Jun 18, 2012 at 10:44
  • 1
    ok, do not go this way... it's a lot of parsing... there is no clean way to do so... you never know, what the user is typing into your textfiel Commented Jun 18, 2012 at 10:45

3 Answers 3

2

Better to use Regular Expression.Not necessary that your String is Array it could be any String which contains numbers.

        String s="{1,2,3,4,5}";
        Pattern p = Pattern.compile("-?\\d+");
        Matcher m = p.matcher(s);
        List<Integer> list=new ArrayList<Integer>();
        while (m.find()) {
          Integer num=new Integer(m.group());

          list.add(num);
        }

        System.out.println(list);

Output:

[1, 2, 3, 4, 5]
Sign up to request clarification or add additional context in comments.

1 Comment

That's true , but he asking generic way so here it is
2

looks like a parse problem to me. look at the string methods :)

the code could look like:

String s = "{1,2,3,4,5}"
String justIntegers = s.substring(1, s.length()-1);
LinkedList<Integer> l = new LinkedList();
for (String string: justIntegers.split(','))
l.add(Integer.valuesOf(string));
l.toArray();

if you are using strings to send/save objects pls use xml or json...

4 Comments

Thanks for the effort, that would work if all I am getting is integer arrays. However I would like a generic solution.
for a generic solution, use "XStream" it's a java-lib to convert java objects to xml-strings and back... just 1 line code each... really usefull
Thanks, I will try that straight away
you can just read/convert xml-Strings... not normal strings... its a way to send/save java-objects via String or byte[]
2

Take a look at https://stackoverflow.com/a/2605050/1458047

The answer proposes a few options.

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.