0

Say I have two string; "fruit;mango;apple;banana" and "animal;dog;cat;cow". What i want is a function to check the first word before 1st semi colon and then if its "fruit" get the other 3 elements(without semi colon) and store it in an array called fruit and if animal take the elements and store is animal array. I thought of using loop and chatAt() but that code will be kinda messy.

So I want to know is there any function to separate a string with char?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Vithushan
  • 503
  • 3
  • 9
  • 34
  • Can you post some code of what you have already tried ? – Florent Bayle Aug 27 '14 at 09:33
  • Hi, I think you should have a look at the [how to ask](http://stackoverflow.com/help/how-to-ask) page, as it'll give you some pointers on how to restructure this question so we can best help. Including some code that you've written would be a good start – Yann Aug 27 '14 at 09:33
  • 2
    You can start from `split` method: `"fruit;a;b;c".split(";")` give you array ["fruit", "a", "b", "c"] – talex Aug 27 '14 at 09:36
  • Your final paragraph seems to be your question - how to split a string. The answer is in the duplicate I've closed this for. I've edited your title accordingly. – Duncan Jones Aug 27 '14 at 09:37

3 Answers3

1

Try this:

String s =  "fruit;mango;apple;banana" ;
String[] elements = s.split(";");
if(elements.length > 0){
    if(elements[0].equals("fruit")){
        String[] fruits = new String[elements.length-1];
        System.arraycopy(elements, 1,fruits , 0, elements.length-1);
        System.out.println(Arrays.toString(fruits));
    }
}
eric
  • 261
  • 1
  • 4
  • 11
1

Here's use following code:

String data="fruit;mango;apple;banana";
    List<String> fruitList=new ArrayList<String>();
    List<String> animalList=new ArrayList<String>();
    String tok[]=data.split(";");
    if(tok[0].equals("fruit"))
    {
        for(int i=1;i<tok.length;i++)
        {
            fruitList.add(tok[i]);
        }
    }
    else
    {
        for(int i=1;i<tok.length;i++)
        {
            animalList.add(tok[i]);
        }
    }
    if(!fruitList.isEmpty())
        System.out.println(fruitList);
    if(!animalList.isEmpty())
        System.out.println(animalList);

Output

[mango, apple, banana]

Now the data string can be any of animal or fruit type.

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
1
String str1 = "fruit;mango;apple;banana";
String str2 = "animal;dog;cat;cow";

String[] arrStr1 = str1.split(";");
String[] arrStr2 = str2.split(";");

ArrayList<String> fruit = null;
if(arrStr1[0].equals("fruit")) {
    fruit = new ArrayList<String>(Arrays.asList(arrStr1));
    fruit.remove("fruit");
}

ArrayList<String> animal = null;
if(arrStr2[0].equals("animal")) {
    animal = new ArrayList<String>(Arrays.asList(arrStr2));
    animal.remove("animal");
}
Jakob
  • 1,129
  • 9
  • 24