Java: How to Split a String by a Number of Characters

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

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;
}

Java - Split String by Number and Letters

You could try this approach:

String formula = "C3H20IO";

//insert "1" in atom-atom boundry
formula = formula.replaceAll("(?<=[A-Z])(?=[A-Z])|(?<=[a-z])(?=[A-Z])|(?<=\\D)$", "1");

//split at letter-digit or digit-letter boundry
String regex = "(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)";
String[] atoms = formula.split(regex);

Output:

atoms: [C, 3, H, 20, I, 1, O, 1]

Now all even even indices (0, 2, 4...) are atoms and odd ones are the associated number:

String[] a = new String[ atoms.length/2 ];
int[] n = new int[ atoms.length/2 ];

for(int i = 0 ; i < a.length ; i++) {
a[i] = atoms[i*2];
n[i] = Integer.parseInt(atoms[i*2+1]);
}

Output:

a: [C, H, I, O]

n: [3, 20, 1, 1]

Java - split after number of characters?

String text = "12345678";
int splitAfter = 3;
List<String> tmpListFirst = new LinkedList<>();
List<String> tmpListSecond = new LinkedList<>();
tmpListFirst.add(text.substring(0, splitAfter));
tmpListSecond.add(text.substring(splitAfter));

That's if you want the values stored in a list. Otherwise they can really be stored in Strings just by doing String s1 = text.substring(0, splitAfter); and
String s2 = text.substring(splitAfter);

Java how to split strings at a space, after a certain number of characters

You can use WordUtils.wrap() method from Apache commons [code]:

Code:

import org.apache.commons.lang3.*;

class WrapTest {
public static void main (String[] args) {
String str = "I am a love cats and dogs but not the flees they carry. Also i think that cats are sometimes rude because they do not hug me when i want them too. Overall though cats and dogs are both great.";
str = WordUtils.wrap(str, 68);
System.out.println(str);
}
}

Output:

I am a love cats and dogs but not the flees they carry. Also i think
that cats are sometimes rude because they do not hug me when i want
them too. Overall though cats and dogs are both great.

How do I split a string in Java?

Use the appropriately named method String#split().

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Note that split's argument is assumed to be a regular expression, so remember to escape special characters if necessary.

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

For instance, to split on a period/dot . (which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).

String[] parts = string.split(Pattern.quote(".")); // Split on the exact string.

To test beforehand if the string contains certain character(s), just use String#contains().

if (string.contains("-")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain -");
}

Note, this does not take a regular expression. For that, use String#matches() instead.

If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.

String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42

How to split a string between letters and digits (or between digits and letters)?

You could try to split on (?<=\D)(?=\d)|(?<=\d)(?=\D), like:

str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

It matches positions between a number and not-a-number (in any order).

  • (?<=\D)(?=\d) - matches a position between a non-digit (\D) and a digit (\d)
  • (?<=\d)(?=\D) - matches a position between a digit and a non-digit.

Splitting a string at every n-th character

You could do it like this:

String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));

which produces:

[123, 456, 789, 0]

The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))



Related Topics



Leave a reply



Submit