CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 2021
    Location
    India
    Posts
    2

    Question A Fast method of Converting String to int array in Java?

    Hi,

    I am using Java V7. Is there a fast way to convert String to int array in Java?

    The Given format is "4 343 234 -24" and so on. Spaces between the numbers, amount of numbers is known beforehand just as is the range within the numbers are

    Code:
    long[] array = new long[length];            
    for (int i = 0; i < length - 1; i++) {
        array[i] = Integer.parseInt(n.substring(0, n.indexOf(' ')));
        n = n.substring(n.substring(0, n.indexOf(' ')).length() + 1);
    }
    array[length - 1] = Integer.parseInt(n);
    Edit: I was going through this resource, could you guys help me with a more relevant resource pertaining to my query?
    Last edited by codighack; October 6th, 2021 at 01:12 PM.

  2. #2
    Join Date
    Oct 2021
    Location
    Pune
    Posts
    1

    Lightbulb Re: A Fast method of Converting String to int array in Java?

    Using String.split() is by far the most efficient when you want to split by a single character (a space, in your case).

    This would be a good solution if you are aiming for maximum efficiency when splitting by spaces.

    Code:
    List<Integer> res = new ArrayList<>();
    Arrays.asList(kraft.split(" ")).forEach(s->res.add(Integer.parseInt(s)));
    Integer[] result = res.toArray(new Integer[0]);
    This works for any number of numbers.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured