Java split string numbers

Split String Every N Characters in Java

In this short article, we are going to explore different ways to split a string every n characters in Java programming language.

First, we will start by taking a close look at solutions using Java 7 and Java 8 methods.

Then, we will shed light on how to accomplish the same thing using external libraries such as Guava.

Using Java 7 Methods

Java 7 provides multiple ways to split a particular string every n characters. Let’s take a close look at every available option.

substring Method

substring, as the name implies, extracts a portion of a string based on given indexes. The first index indicates the starting offset and the second one denotes the last offset.

Typically, we can use substring method to split our string into multiple parts every n characters.

Let’s see this method in action by writing a basic example:

 public static void main(String[] args) < String myString = "Hello devwithus.com"; int nbrOfChars = 5; for (int i = 0; i < myString.length(); i += nbrOfChars) < String part = myString.substring(i, Math.min(myString.length(), i + nbrOfChars)); System.out.println("Portion: " + part); > > 

Split using substring method

Now, let’s investigate a little bit our example. As we can see, we iterate through myString and extract every nbrOfChars characters in a separate substring.

Please note that Math.min(myString.length(), i + nbrOfChars) returns the remaining characters at the end.

Pattern Class

Pattern class represents a compiled regular expression. In order to achieve the intended purpose, we need to use a regex that matches a specific number of characters.

For instance, let’s consider this example:

 public static void main(String[] args) < String myString = "abcdefghijklmno"; int nbr = 3; Pattern pattern = Pattern.compile(". + nbr + ">"); Matcher matcher = pattern.matcher(myString); while (matcher.find()) < String part = myString.substring(matcher.start(), matcher.end()); System.out.println("Portion starting from " + matcher.start() + " to " + matcher.end() + " : " + part); > > 

Split using pattern class

The regex . denotes at least one character but not more than n characters.

The idea is to create a Matcher object for the pattern and use it to match our string against our regex: . .

As shown above, we used substring for each matcher found to extract every portion of string starting from matcher.start() to matcher.end().

split Method

Similarly, we can use split method to answer our central question. This method relies on the specified delimiter or regular expression to divide a string into several subregions.

The best way to split a string every n characters is to use the following positive lookbehind regex: (?<=\G…) , where denotes three characters.

Now, let’s illustrate the use of the split method with a practical example:

 public static void main(String[] args) < String myString = "foobarfoobarfoobar"; String[] parts = myString.split("(?for (String part : parts) < System.out.println("Portion : " + part); > > 

Split string using split method

Please bear in mind that we can replace the three dots with ”.”. If we want to make the number of characters dynamic, we can specify: (?)

Using Java 8

Java 8 offers a another great alternative to divide a string every certain number of characters.

The first step consists on calling the chars method. Then, with the help of the Stream API, we can map and group every character using AtomicInteger class and a collector.

Please note that Collectors.joining() is a collector that concatenates chars into a single string.

 public static void main(String[] args) < AtomicInteger nbrOfChars = new AtomicInteger(0); String myString = "zzz111aaa222ddd333"; myString.chars() .mapToObj(myChar -> String.valueOf((char) myChar)) .collect(Collectors.groupingBy(myChar -> nbrOfChars.getAndIncrement() / 3, Collectors.joining())) .values() .forEach(System.out::println); > 

Using Guava Library

Guava is a handy library that provides a set of ready-to-use helper classes. Among these utility classes, we find the Splitter class.

Splitter provides the fixedLength() method to split a string into multiple portions of the given length.

Let’s see how we can use Guava to split a String object every n characters:

 public static void main(String[] args) < String myString = "aaaabbbbccccdddd"; Iterable parts = Splitter.fixedLength(4).split(myString); parts.forEach(System.out::println); > 

Conclusion

To sum it up, we explained in detail how to split a string at every nth character using Java 7 ⁄8 methods.

After that, we showed how to accomplish the same objective using the Guava library.

Liked the Article? Share it on Social media!

If you enjoy reading my articles, buy me a coffee ☕. I would be very grateful if you could consider my request ✌️

Источник

Java String split() Method with examples

Java String split method is used for splitting a String into substrings based on the given delimiter or regular expression.

For example:

Input String: [email protected] Regular Expression: @ Output Substrings:

Java String Split Method

Java Split Method Examples

We have two variants of split() method in String class.

1. String[] split(String regex) : It returns an array of strings after splitting an input String based on the delimiting regular expression.

2. String[] split(String regex, int limit) : This method is used when you want to limit the number of substrings. The only difference between this variant and above variant is that it limits the number of strings returned after split up. For example: split(«anydelimiter», 3) would return the array of only 3 strings even if there can be more than three substrings.

What if limit is entered as a negative number?
If the limit is negative then the returned string array would contain all the substrings including the trailing empty strings, however if the limit is zero then the returned string array would contains all the substrings excluding the trailing empty Strings.

It throws PatternSyntaxException if the syntax of specified regular expression is not valid.

String split() method Example

If the limit is not defined:

Java String split method

If positive limit is specified in the split() method: Here the limit is specified as 2 so the split method returns only two substrings.

String split strings with a limit

If limit is specified as a negative number: As you can see that when the limit is negative, it included the trailing empty strings in the output. See the output screenshot below.

String split when limit is set to negative

Limit is set to zero: This will exclude the trailing empty strings.

output

Difference between zero and negative limit in split() method:

  • If the limit in split() is set to zero, it outputs all the substrings but exclude trailing empty strings if present.
  • If the limit in split() is set to a negative number, it outputs all the substrings including the trailing empty strings if present.

Java String split() method with multiple delimiters

Let’s see how we can pass multiple delimiters while using split() method. In this example we are splitting input string based on multiple special characters.

Number of substrings: 7 Str[0]: Str[1]:ab Str[2]:gh Str[3]:bc Str[4]:pq Str[5]:kk Str[6]:bb

Lets practice few more examples:

Java Split String Examples

Example 1: Split string using word as delimiter

Here, a string (a word) is used as a delimiter in split() method.

Example 2: Split string by space

String[] strArray = str.split("\\s+");
Input: "Text with spaces"; Output: ["Text", "with", "spaces"]

Example 3: Split string by pipe

String[] strArray = str.split("\\|");
Input: "Text1|Text2|Text3"; Output: ["Text1", "Text2", "Text3"]

Example 4: Split string by dot ( . )

String[] strArray = str.split("\\.");

You can split string by dot ( . ) using \\. regex in split method.

Input: "Just.a.Simple.String"; Output: ["Just", "a", "Simple", "String"]

Example 5: Split string into array of characters

String[] strArray = str.split("(?!^)");

The ?! part in this regex is negative assertion, which it works like a not operator in the context of regular expression. The ^ is to match the beginning of the string. Together it matches any character that is not the beginning of the string, which means it splits the string on every character.

Input: "String"; Output: ["S", "t", "r", "i", "n", "g"]

Example 6: Split string by capital letters

String[] strArray = str.split("(?=\\p)");

\p is a shorthand for \p . This regex matches uppercase letter. The extra backslash is to escape the sequence. This regex split string by capital letters.

Input: "BeginnersBook.com"; Output: ["Beginners", "Book.com"]

Example 7: Split string by newline

String[] str = str.split(System.lineSeparator());

This is one of the best way to split string by newline as this is a system independent approach. The lineSeparator() method returns the character sequence for the underlying system.

Example 8: Split string by comma

String[] strArray = str.split(",");

To split the string by comma, you can pass , special character in the split() method as shown above.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

Is it right to say that 28 is present at array1[0], 12 at array1[1] and 2013 at array1[2]?
I am really confused right now.Please help.

It would be helpful to include some examples that require use of the escape characters and which characters need them. It is one thing I was looking for. Once I realized that “|” needed “\\|”, my split worked like a champ. Thanks for showing these using small code bits. It really does make a difference.

Источник

Читайте также:  Html language image link
Оцените статью