0

given an array

String original[]={"string0,10","string1,45","string2,3", "string3,67"};

how would I use the comma as a delimeter to create another array with only the names?

I need an array that looks something like this:

String result[]={"string0","string1","string2", "string3"};
4
  • so the second line is your desired output? Have you tried this ? Commented Nov 9, 2018 at 7:33
  • Will the name be always the first part of each item? Commented Nov 9, 2018 at 7:43
  • @Jibran yes but the name can also have numbers and special characters. I just need to figure out how to get the substring up until the comma at each index of the original array. Commented Nov 9, 2018 at 7:45
  • You can try java 8 solution given below by @schidu. It is elegant and will do the work. Commented Nov 9, 2018 at 7:48

3 Answers 3

3

You can use streams and map from java 8 to do it:

String[] strings = Arrays.stream(test)
            .map(string -> string.split(",")[0])
            .toArray(String[]::new);
Sign up to request clarification or add additional context in comments.

Comments

0
public static void main(String[] args) {
    String original[]={"string0,10","string1,45","string2,3", "string3,67"};
    int len = original.length;
    String result[] = new String[len];
    for(int i=0; i<len;i++) {       
        result[i] = original[i].split(",")[0];      
    }

    System.out.println(Arrays.toString(result));
}
  1. DeclareString result[] array
  2. Iterate the array
  3. Split the record for every Iteration using , as delimiter
  4. Now the split operation will return the array of size 2. It contains name at index 0.
  5. assign the value the result array.

1 Comment

I would add a check before the assignment to result[I] as depending on the content of original[] there may not be a ',' and you should always check for the possibility of this not being present.
0
import java.util.Arrays;
import java.util.stream.Collectors;

public class ArraySubstring {

    public static void main (String args[]) {
        String test[]={"string0,10","string1,45","string2,3", "string3,67"};

        String test2[] = Arrays.stream(test).map(s -> s.substring(0, s.indexOf(","))).toArray(String[]::new);
        for (String s : test2) {
            System.out.println(s);
        }
    }
}

1 Comment

I agree this can be much simplified as @Schidu mentioned.

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.