0

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?

8 Answers 8

2

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]
Sign up to request clarification or add additional context in comments.

2 Comments

can you tell me how to add this is array?
I didn't see this solution. Looks like we thought the same solution ;) Which is positive :)
1

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;
    }

2 Comments

Its simple answer without String builder
Is a better solution use StringBuilder. Also u are adding empty strings in case there are in the array.
1

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("-");

2 Comments

Smarter to use the string builder, but using the sop iterator to pull from the s[], is the problem with the code provided.
I dont know why I can't make the later part as a code .. can anybody help?
0

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++;
          }
      }
     }

Comments

0

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);
}

3 Comments

Well I guess if you have a full string you can as well use s_full.split("-")
@Joffrey Oh yes.. That would be simpler I guess. :)
Indeed, it would take one line ^^
0

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++;
    }

}

Comments

0

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...

Comments

0

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]);

1 Comment

I didn't see the solution from Harmlezz. Looks like we thought the same solution ;)

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.