iluzek
iluzek

Reputation: 35

Java-Split characters from a String into an Array of Strings

    import java.io.*;

    public class Test{
       public static void main(String args[]){
          String Str = new String("Welcome to Tutorialspoint.com and again some other random stuff in this string.");
          String[] result= new String[8];
          byte c=0b0;
          int i=0;
          int j=0;

          for (int a=0;a<7;a++){
              result[a]="";
          }
          for(i=0; j<Str.length(); j++){
              c=(byte)(Str.charAt(j));  
              result [i]+=(char)c;
              if (i<7){i++;}else{i=0;}
          }
          for (int a=0;a<8;a++){
              System.out.println(result[a]);
          }
       }
    }

The goal is to create 8 strings from the original string. String[0] will hold characters 0,8,16,...and so on. String[1] will hold characters 1,9,17,...and so on. I hope this is clear enough.

What I get with this code is something I cannot seem to overcome.

    Wtitdsemis
    eoa. or nt
    l lcam s r
    cTsogertti
    oupma auhn
    mto ionfig
    eoiantdfs.
    null rnn ho  

Notice null in last line - I need this gone as string should start with ' rnn ho' just like this.

    Wtitdsemis
    eoa. or nt
    l lcam s r
    cTsogertti
    oupma auhn
    mto ionfig
    eoiantdfs.
     rnn ho 

Would really appreciate if someone pointed out how to not get this output. This is a 'test' code for splitting a String that will hold values from -126 to 127 binary. Not all of them will be printable and I need them to still be split correctly. For the most part code seems to work except for those seemingly random 'null' strings in output.

I do not mind [null]=0 characters as long as they take 1 character space and not 4 in one String.

================================================================================== Initializing a<8 fixed this problem. But I did not even have time to read all other comments/answers. Did not expect such fast answers. THANK YOU ALL . I will up vote any relevant solution when I read them all and/or get reputation required.

================================================================================== FIXED!.

================================================================================== Selected answer of Ian McLaird as not only it fixed my 'silly' mistake but also showed me neater code and functionality that I did not know about. Regardless thank you all for comments and answers.

Upvotes: 0

Views: 1050

Answers (3)

nitishagar
nitishagar

Reputation: 9413

You can try the following:

import java.io.*;

public class Test{
  public static void main(String args[]){
    String Str = new String("Welcome to Tutorialspoint.com and again some other random stuff in this string.");

    String[] result = new String[8];

    for (int a = 0; a < result.length; a++)
       result[a] = "";

    char[] chars = str.toCharArray();
    for (int i = 0; i < chars.length; ++i) 
      result[i % result.length] += chars[i];

    for (int a = 0; a < result.length; a++)
      System.out.println(result[a]);
  }
}

Resulting output will be:

Wtitdsemis
eoa. or nt
l lcam s r
cTsogertti
oupma auhn
mto ionfig
eoiantdfs.
 rnn ho

Upvotes: 0

Ian McLaird
Ian McLaird

Reputation: 5585

How about this?

public class StringSplitter {
    public static void main(String[] args) {
        String str = new String("Welcome to Tutorialspoint.com and again some other random stuff in this string.");
        String[] result = new String[8];

        for (int i = 0; i < result.length; ++i) {
            result[i] = "";
        }

        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; ++i) {
            result[i % result.length] += chars[i];
        }

        for (int i = 0; i < result.length; ++i) {
            System.out.println(result[i]);
        }
    }
}

Since your result array is already instantiated, it's safe to use the length property to initialize the elements to empty strings. Since you intend to process each character in the string, go ahead and just get it as an array, and then use the modulus operator to put each character into its proper place in the result array. As an added benefit, it's also safe against changing the length of the result array. Hard-coded loop sentinels are dangerous.

Output

Wtitdsemis
eoa. or nt
l lcam s r
cTsogertti
oupma auhn
mto ionfig
eoiantdfs.
 rnn ho  

Upvotes: 1

robm
robm

Reputation: 1

From a quick glance at your code, the issue is that in your first for loop you're instantiating result[0] to result[6] and not instantiating result[7]. When you put for (int a = 0; a <7; a++) the loop will run until a = 6 - when it gets increased to 7 a<7 returns false so after the first for loop, result[7]==null

Upvotes: 0

Related Questions