How to Split a String in Java ?

Hello coder , Today we are going to learn how to split any given string by number of characters in java , So let’s get started.

What does Split string by number of characters means ?

Split string by number of characters means, we convert a string into a substring array on the basis of number of character you choose for the substring . For e.g. You are a given a string, S = “0000111110100001” and you need to convert the string in a substring array where length of substring is 4. The output or the substring array will be [“0000”, “1111”, “1010”, “0001”]. This is the output which you can expect when you need to split the given string and convert it into a list of substrings having a length of 4.

Now, let’s see different ways to perform the given operation to split string on the basis of number of characters.

Using a loop : Basic Java

Let the given string be s = “Hello how are you?” , then the following code to split into a substring array by number of character will be : If the number of character of the substrings will be 4.

CODE :

     String text = "Hello how are you?"
     List<String> strings = new ArrayList<String>();
     int index = 0;
     while (index < text.length()) {
          strings.add(text.substring(index, Math.min(index + 4,text.length())));
          index += 4;
     }

OUTPUT :

   ["Hell", "o ho", "w ar", "e yo" ,"u?"]

Using Guava :

Guava is a set of core Java libraries from Google that includes new collection types (such as multimap and multiset), immutable collections, a graph library, and utilities for concurrency, I/O, hashing, caching, primitives, strings, and more! By using Guava we can the do the following task very easily.

     for(final String token :
         Splitter
             .fixedLength(4)
             .split("Thequickbrownfoxjumps")){
         System.out.println(token);
     }

OUTPUT :

   Theq
   uick
   brow
   nfox
   jump
   s

If you want the result in the form an array , then see this code :

    String[] tokens =
       Iterables.toArray(
          Splitter
              .fixedLength(4)
              .split("Thequickbrownfoxjumps"),
          String.class
      );

One more way using Guava is ,

     Iterable<String> result = Splitter.fixedLength(4).split("Hello how are you?");
     String[] parts = Iterables.toArray(result, String.class);

Using Regex :

One more way on reaching the same result is by making the use of regex in java. Using regex the given problem can be solved in one line step. See this code ,

     String s = "Hello how are you?";
     int size = 4;
     String[] tokens = s.split("(?<=\\G.{" + size + "})");

You can also make a function for doing the same using regex ,

    public static String[] splitByNumber(String str, int size) {
        return (size<1 || str==null) ? null : str.split("(?<=\\G.{"+size+"})");
   }

So, these are all the methods that you can use to perform the given task to split the given string by the number of characters !

Thanks for reading and learning with www.codingbroz.com , please check our other articles and solutions too !

Broz Who Code !!

CodingBroz

Leave a Comment

Your email address will not be published. Required fields are marked *