3

i tried myself lot but can't get a solution so i'm asking help.

i have an string String input="---4--5-67--8-9---";

now i need to convert in into an string array which will look like:

String [][]output={{4},{5},{67},{8},{9}};

i tried with split() and

java.util.Arrays.toString("---4--5-67--8-9---".split("-+")

but can't find the desired answer. so what to do?

actually i need the value 4,5,67,8,9.but i'm not sure how to find them. i will treat the values as integer for further processing

3
  • 3
    Why do you want an array of arrays if each subarray contains just one element? Commented Aug 31, 2010 at 7:55
  • actually i need the value 4,5,67,8,9.but i'm not sure how to find them. i will treat the values as integer for further processing Commented Aug 31, 2010 at 8:00
  • 2
    well then you want an array of ints or integers, not a two-dimensional string array Commented Aug 31, 2010 at 8:14

8 Answers 8

5
String[] numbers = "---4--5-67--8-9---".split("-+");
String[][] result = new String[numbers.length][1];
for (int i = 0; i < numbers.length; i++) {
    result[i][0] = numbers[i];
}

Update: to get rid of the initial empty value, you can get a substring of the input, like:

int startIdx = 0;
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i ++) {
    if (Character.isDigit(chars[i])) {
        startIdx = i;
        break;
    }
}
input = input.substring(startIdx);

(or you can check them for not being empty (String.isEmpty()) when processing them later.)

Sign up to request clarification or add additional context in comments.

1 Comment

returns [[], [4], [5], [67], [8], [9]](there is an empty array at the beginning)
4

First, here is the answer to your question. This code will generate a two-dimensional array where each element is an array consisting of a single numeric string.

final String input = "---4--5-67--8-9---";
// desired output: {{4},{5},{67},{8},{9}}

// First step: convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
    input.replaceAll("\\D+", " ").trim().split(" ");

// Now create the two-dimensional array with the correct size
final String[][] arrayOfArrays = new String[arrayOfStrings.length][];

// Loop over single-dimension array to initialize the two-dimensional one
for(int i = 0; i < arrayOfStrings.length; i++){
    final String item = arrayOfStrings[i];
    arrayOfArrays[i] = new String[] { item };
}
System.out.println(Arrays.deepToString(arrayOfArrays));
// Output: [[4], [5], [67], [8], [9]]

However, I think what you really need is an array of Integers or ints, so here is a revised solution:

final String input = "---4--5-67--8-9---";

// Convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
    input.replaceAll("\\D+", " ").trim().split(" ");

// Now create an array of Integers and assign the values from the string
final Integer[] arrayOfIntegers = new Integer[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
    arrayOfIntegers[i] = Integer.valueOf(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfIntegers));
// Output: [4, 5, 67, 8, 9]

// Or alternatively an array of ints
final int[] arrayOfInts = new int[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
    arrayOfInts[i] = Integer.parseInt(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfInts));
// Output: [4, 5, 67, 8, 9]

Whether you use the Integer or the int version really depends on whether you want to just do some math (int) or need an object reference (Integer).

Comments

3
String[] result = "---4--5-67--8-9---".split("-+");
int i;
for (i = 0; i < result.length; i++) {
    if (result[i].length() > 0) {
        System.out.println(result[i]);
    }
}

gives me output:

4
5
67
8
9

4 Comments

that's not really an answer to the question, though
@seanizer: Since the string array "result" has the desired content apart from the starting empty string I disagree.
apart from the starting empty string, exactly. but apparently yours is the best answer from the OP's point of view anyway
The question is "what to do" followed by "I need the values". I would say it's a pretty good answer :)
1
public class split{
public static void main(String[] argv){
    String str="---4--5-67--8-9---";
    String[] str_a=str.split("-+");
}

}

This seems to working for me.

Comments

1

Using a regex pattern seems more natural in this case:

public class split {
     public static int[] main(String input) {

         ArrayList<String> list = new ArrayList() ;

         Pattern pattern = Pattern.compile("[0-9]") ;
         Matcher matcher = pattern.matcher(input) ;

         String match = null ;

             while(  ( match = matcher.find() )  ===  true  ) {
                 list.add(match) ;
             }

         String[] array = list.toArray(   new String[  ( list.size() )  ]()   ) ;

         return array ;

     }
}

Comments

1
    String input="---4--5-67--8-9---";
    Scanner scanner = new Scanner(input).useDelimiter("-+");
    List<Integer> numbers = new ArrayList<Integer>();
    while(scanner.hasNextInt()) {
        numbers.add(scanner.nextInt());
    }
    Integer[] arrayOfNums = numbers.toArray(new Integer[]{});
    System.out.println(Arrays.toString(arrayOfNums));

Comments

1

I thought the following is quite simple, although it uses List and Integer arrays, Its not that an overhead for small strings:

For simplicity, I am returning a single dimension array, but can be easily modified to return an array you want. But from your question, it seems that you just want a list of integers.

import java.util.*;

public class Test {

    public static void main(String[] args) throws Throwable {
         String input = "---4--5-67--8-9---";
         System.out.println(split(input).length); // 5
    }

    public static Integer[] split(String input) {
         String[] output = input.split("\\-+");
         List<Integer> intList = new ArrayList<Integer>(output.length);

         // iterate to remove empty elements
         for(String o : output)  {
            if(o.length() > 0)   {
               intList.add(Integer.valueOf(o));
            }
         }
         // convert to array (or could return the list itself
         Integer[] ret = new Integer[intList.size()];
         return intList.toArray(ret);
    }
}

Comments

1

I might be late to the party but I figured I'd give the guava take on this.

    String in = "---4--5-67--8-9---";

    List<String> list = Lists.newArrayList(Splitter.on("-").omitEmptyStrings().trimResults().split(in));
    System.out.println(list);
    // prints [4, 5, 67, 8, 9]

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.