Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to split a string by a number of characters?

I tried to search online to solve this question but I didn't found anything.

I wrote the following abstract code to explain what I'm asking:

String text = "how are you?";  String[] textArray= text.splitByNumber(4); //this method is what I'm asking textArray[0]; //it contains "how " textArray[1]; //it contains "are " textArray[2]; //it contains "you?" 

The method splitByNumber splits the string "text" every 4 characters. How I can create this method??

Many Thanks

like image 454
Meroelyth Avatar asked Feb 14 '12 12:02

Meroelyth


People also ask

Can you split a string by multiple characters Java?

Java String split() The String split() method returns an array of split strings after the method splits the given string around matches of a given regular expression containing the delimiters. The regular expression must be a valid pattern and remember to escape special characters if necessary.

How do you split a string into number of characters?

String text = "how are you?"; String[] textArray= text. splitByNumber(4); //this method is what I'm asking textArray[0]; //it contains "how " textArray[1]; //it contains "are " textArray[2]; //it contains "you?" The method splitByNumber splits the string "text" every 4 characters.

Can a string be split on multiple characters?

Method 1: Split multiple characters from string using re. split() This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.


2 Answers

I think that what he wants is to have a string split into substrings of size 4. Then I would do this in a loop:

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; } 
like image 120
Guillaume Polet Avatar answered Sep 20 '22 19:09

Guillaume Polet


Using Guava:

Iterable<String> result = Splitter.fixedLength(4).split("how are you?"); String[] parts = Iterables.toArray(result, String.class); 
like image 23
bruno conde Avatar answered Sep 19 '22 19:09

bruno conde