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
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.
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.
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.
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; }
Using Guava:
Iterable<String> result = Splitter.fixedLength(4).split("how are you?"); String[] parts = Iterables.toArray(result, String.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With