HackJavaMagicNumber
HackJavaMagicNumber

Reputation: 57

How to split String array and store the string in another array

I have a string array which contains "-" . So I have to split these strings to store them.

For example.

String s[]={"a","b","c","-","g","t","-","q","-","a","s","d","-","a","b","y"};

to

String k[]={"abc","gt","q","asd","aby"}

The code I have tried is

 public static void main(String...a)
{


String s[]={"a","b","c","-","g","t","-","q","-","a","s","d","-","a","b","y"};

int sop=0;

                 String[] sdf=new String[100];

 for(int kk=0;kk<s.length;kk++)
             {

              if(s[sop].equals("-"))
              {

              }
              else
              {
              sdf[sop]=s[sop];

               sop++;
              }

             }
}

But It gives first three string. abc. What I have to add?

Upvotes: 0

Views: 1955

Answers (8)

Javier Salinas
Javier Salinas

Reputation: 657

I'd something like that:

String s[] = { "a", "b", "c", "-", "g", "t", "-", "q", "-", "a", "s", "d", "-", "a", "b", "y" };
String delimiter = "-";

List<String> result = new ArrayList<String>();  
StringBuilder group = new StringBuilder();
for (String character : s) {
    if (delimiter.equals(character) && !"".equals(group)) {
        result.add(group.toString());
        group.setLength(0);
    } else {
        group.append(character);
    }
}

if (!"".equals(group)) {
    result.add(group.toString());
}

You could use List or an array string converting using:

result.toArray(new String[0]);

Upvotes: 0

Error418
Error418

Reputation: 309

You could do that :

    String s[]={"a","b","c","-","g","t","-","q","-","a","s","d","-","a","b","y"};

    String split = "-";

    ArrayList<String> list = new ArrayList<String>();
    String temp = "";

    for(int i = 0 ; i < s.length ; i++){
        if(s[i].equals(split)){
            list.add(temp);
            temp = new String();
        }else{
            temp += s[i];
        }
    }

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

    for(String str : array){
        System.out.println(str); // output : abc;gt;q;asd;
    }

Upvotes: 1

Julian Habekost
Julian Habekost

Reputation: 272

Staying in your context:

public static void main(String[] a) {


    String s[]={"a","b","c","-","g","t","-","q","-","a","s","d","-","a","b","y"};

    int sop=0;

    String[] sdf=new String[100];
    String temp = "";

    for(int kk=0;kk<s.length;kk++){
        if(s[kk].equals("-")){
            sdf[sop] = temp;
            temp = "";
            sop++;
        } else {
            temp += s[kk];
        }
    }
}

Better use a StringBuilder, this is just for understanding the logic...

Upvotes: 0

Joffrey
Joffrey

Reputation: 37710

Several problems here:

  • you stop incrementing sop when you reach a "-". I think instead of s[sop] you might want to use s[kk].
  • each time you get new characters, you don't append them to an existing string, but you add them in new array cells

Also, for your second array, consider using an ArrayList, as you don't initially know its size.

Here is a corrected version:

for (int kk = 0; kk < s.length; kk++) {

    if (!s[kk].equals("-")) {
        if (sdf[sop] != null) {
            sdf[sop] += s[kk];
        } else {
            sdf[sop] = s[kk];
        } 
    } else {
        sop++;
    }

}

Upvotes: 0

stinepike
stinepike

Reputation: 54682

you are not incrementing the sop if s[sop].equals("-"). you have to increment it everytime. and also it can be reduced to.

          if(!s[sop].equals("-"))
          {
              sdf[sop]=s[sop];
          }
          sop++;

also instead of sop you can use the loop counter kk;

another alternative way can be,

  1. iterate through the first array and contact all element to a String.
  2. get the final array using String.split method

    StringBuilder sB = new StringBuilder();
    for(String temp : s)
    sB.append(temp);
    String[] output = sB.toString().split("-");

Upvotes: 1

Harmlezz
Harmlezz

Reputation: 8068

You may try it this way:

public static void main(String[] args) {
    String[] s = {"a","b","c","-","g","t","-","q","-","a","s","d","-","a","b","y"};
    StringBuilder builder = new StringBuilder();
    ArrayList<String> k = new ArrayList<String>();
    for (String str : s) {
        if (str.equals("-")) {
            k.add(builder.toString());
            builder.setLength(0);
        } else builder.append(str);
    }
    k.add(builder.toString());
    System.out.println(Arrays.toString(k.toArray(new String[k.size()])));
}

OUTPUT:

[abc, gt, q, asd, aby]

Upvotes: 2

wns349
wns349

Reputation: 1306

Do you have to start off with a string array?

You might want to use StringTokenizer to parse your string with '-'.

String s[] = { "a", "b", "c", "-", "g", "t", "-", "q", "-", "a", "s",
                "d", "-", "a", "b", "y" };

// Join the letters to make a full string
String s_full = "";
for (String letter : s) {
    s_full += letter;
}

StringTokenizer st = new StringTokenizer(s_full, "-");  //Tokenize
String[] words = new String[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
    words[i++] = st.nextToken();    //Add to result array
}

// Print result
for (String word : words) {
    System.out.println(word);
}

Upvotes: 0

Patrick J Abare II
Patrick J Abare II

Reputation: 1129

Logic error: You were using the same iterator in both arrays, while retrieving the value from s[], you should be using the for loop iterator, kk.

public static void main(String...a)
     {
     String s[]={"a","b","c","-","g","t","-","q","-","a","s","d","-","a","b","y"};

     String[] sdf=new String[100];
     int sop = 0;
      for(int kk=0;kk<s.length;kk++)
      {
          if(!s[kk].equals("-"))
          {
              sdf[sop]=s[kk];
              sop++;
          }
      }
     }

Upvotes: 0

Related Questions