Convert char array to multiple strings

I need to convert a char array to multiple strings of a specific size. For example, given this array:

char[] bases = new char[]{'a', 'c', 'c', 't', 'a', 'c', 'a', 't', 'a', 'c', 'c', 't', 'a', 'c', 'a', 't'};

      

the expected result will be 5 :

accta
catac
ctaca

      

I am currently using this code:

    int ls = 5; 
    String str = ""; 
    for (int i = 1; i < bases.length; i++) {
        str += bases[i - 1];
        if (i%ls == 0) {
            str += '\n';
        }
    }

      

Is there a built-in function to achieve this in java 8? Is there a better way to solve this problem?

+3


source to share


5 answers


You can convert string char[]

to string then you can use split with some regex like:

String s = String.valueOf(bases);//result = acctacatacctacat
System.out.println(Arrays.toString(s.split("(?<=\\G.{5})")));

      

If you want to do it in one line:



String[] spl = String.valueOf(bases).split("(?<=\\G.{5})");

      

Output

[accta, catac, ctaca, t]

      

+5


source


You could probably use substring () to simplify it. (First convert char [] to string)



 int ls = 5; 
 for (int i = ls; i < bases.length; i+=ls)
     someList.append(bases.substring((i-ls, i)));

      

+2


source


You should almost never use string concatenation in a loop to construct a string.

Use StringBuilder

:

StringBuilder sb = new StringBuilder(bases.length + (4 + bases.length) / 5);
for (int i = 0; i < bases.length; i += 5) {
  sb.append(bases, i, Math.min(5, bases.length - i));
  sb.append("\n");
}
String str = sb.toString();

      

+2


source


Since in this case you have a very clear idea of ​​the sequence you need to create, it may be most efficient to use your own code to create the appropriate one char[]

:

   final int ls = 5;
   final char[] result = new char[bases.length + (bases.length + ls - 1) / ls]
   int nextIndex = 0;
   for (int i = 0; i < bases.length; i += ls) {
      final int size = bases.length - i >= ls ? ls : bases.length - i;
      System.arraycopy(bases, i, result, nextIndex, size);
      nextIndex += size;
      result[nextIndex++] = '\n'; 
   }
   final String resultAsString = new String(result);

      

0


source


This could be a different solution to your question using the power of java8 stream: (for understanding, I'll leave the answer step by step, but a lot can be condensed and simplified / collected later)

int charsPerChunk = 5;
char[] myCharArray = { 'H', 'e', 'l', 'l', 'o', '+', 'X', 'o', 'c', 'e', '!' };
// turn the char array into a Stream of Characters
Stream<Character> myStreamOfCharacters = IntStream.range(0, myCharArray.length).mapToObj(i -> myCharArray[i]);
// collect that into a list of characters
List<Character> myListOfCharacters = myStreamOfCharacters.collect(Collectors.toList());

int size = myListOfCharacters.size();
int fullChunks = (size - 1) / charsPerChunk;
// get a stream of list of characters
Stream<List<Character>> result = IntStream
          .range(0, fullChunks + 1)
          .mapToObj( x -> myListOfCharacters.subList(x * charsPerChunk, x == fullChunks ? size : (x + 1) * charsPerChunk));

// print it
result.forEach(System.out::println);

      

0


source







All Articles