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.
for (int a=0;a<=7;a++). You don't initialize that last String.charAttobyteand then casting thebyteto achar?charAtalready returns the type you want, and those conversions aren't safe.charis 16 bits in Java andbyteis only 8.